Home > Java > javaTutorial > body text

Detailed explanation of the operation code to wake up notifyAll in Java thread

黄舟
Release: 2017-03-25 10:40:58
Original
1334 people have browsed it

This article mainly introduces the notifyAll wake-up operation in Java threads. It is very good and has reference value. Friends in need can refer to it

Note:

NotifyAll and notify in java are operations to wake up threads. notify will only wake up a certain thread in the waiting pool, but it is not sure which thread it is. notifyAll is for the specified objectAll threads inside perform wake-up operations. Once the specified object is woken up successfully. It will immediately join the thread's resource competition.

For example:

package TestThread.ThreadSynchronized;
public class TestWaitAll {
 public static void main(String[] args) {
  Test1 test1 = new Test1();
  Thread t = new Thread(test1, "线程1");
  Thread t1 = new Thread(test1, "线程2");
  Thread t2 = new Thread(test1, "线程3");
  Test2 test2 = new Test2(test1, "唤醒线程");
  t.start();
  t1.start();
  t2.start();
  try {
   Thread.sleep(2000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  test2.start();
 }
}
class Test1 implements Runnable {
 public void run() {
  synchronized (this) {
   try {
    this.wait();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   System.out.println(Thread.currentThread().getName() + "当前没有被执行到!");
  }
 }
}
class Test2 extends Thread {
 private Test1 test1;
 String name;
 public Test2(Test1 test1, String name) {
  super(name);
  this.name = name;
  this.test1 = test1;
 }
 public void run() {
  synchronized (test1) {
   test1.notifyAll();// 针对当前对象执行唤醒所有线程的操作
   System.out.println(Thread.currentThread().getName() + ":唤醒线程执行成功!");
  }
 }
}
Copy after login

The execution result is:

Detailed explanation of the operation code to wake up notifyAll in Java thread

The above is the detailed content of Detailed explanation of the operation code to wake up notifyAll in Java thread. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!