成都网站建设设计

将想法与焦点和您一起共享

Java线程中的notifyAll唤醒操作(推荐)

注意:

创新互联是专业的睢阳网站建设公司,睢阳接单;提供成都做网站、成都网站建设,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行睢阳网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!

java中的notifyAll和notify都是唤醒线程的操作,notify只会唤醒等待池中的某一个线程,但是不确定是哪一个线程,notifyAll是针对指定对象里面的所有线程执行唤醒操作,指定对象一旦唤醒成功。则会立即加入线程的资源争夺中去。

例如:

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() + ":唤醒线程执行成功!");
  }
 }
}

 执行结果为:

Java线程中的notifyAll唤醒操作(推荐)

以上所述是小编给大家介绍的Java线程中的notifyAll唤醒操作,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对创新互联网站的支持!


当前名称:Java线程中的notifyAll唤醒操作(推荐)
新闻来源:http://chengdu.cdxwcx.cn/article/ggdipg.html