java中的notifyAll和通知都是唤醒线程的操作,通知只会唤醒等待池中的某一个线程,但是不确定是哪一个线程,notifyAll是针对指定对象里面的所有线程执行唤醒操作,指定对象一旦唤醒成功。则会立即加入线程的资源争夺中去。
例如:
包TestThread.ThreadSynchronized; 公开课TestWaitAll { 公共静态void main (String [] args) { Test1 Test1=new Test1 (); 线程t=新线程(test1,“线程1 "); 线程t1=新线程(test1,“线程2”); 线程t2=新线程(test1,“线程3”); Test2 Test2=new Test2 (test1,“唤醒线程”); t.start (); t1.start (); t2.start (); 尝试{ thread . sleep (2000); }捕捉(InterruptedException e) {//TODO自动生成的catch块 e.printStackTrace (); } test2.start (); } } 类Test1实现Runnable { 公共空间run () { 同步(){ 尝试{ this.wait (); }捕捉(InterruptedException e) { e.printStackTrace (); } System.out.println (Thread.currentThread () . getname() +”当前没有被执行到!”); } } } 类Test2延伸线程{ 私人Test1 Test1; 字符串名称; 公共Test2 (Test1 Test1,字符串名称){ 超级(名称); this.name=名称; 这一点。test1=test1; } 公共空间run () { 同步(test1) { test1.notifyAll();//针对当前对象执行唤醒所有线程的操作 System.out.println (Thread.currentThread () . getname() +”:唤醒线程执行成功!”); } } }
,执行结果为:
以上所述是小编给大家介绍的Java线程中的notifyAll唤醒操作,希望对大家有所帮助,如果大家有任何疑问请给我留的言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!