当前位置: 移动技术网 > IT编程>开发语言>Java > Java线程中的notifyAll唤醒操作(推荐)

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

注意:

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唤醒操作,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网