您好,登錄后才能下訂單哦!
注意:
java中的notifyAll和notify都是喚醒線程的操作,notify只會喚醒等待池中的某一個線程,但是不確定是哪一個線程,notifyAll是針對指定對象里面的所有線程執(zhí)行喚醒操作,指定對象一旦喚醒成功。則會立即加入線程的資源爭奪中去。
例如:
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() + "當(dāng)前沒有被執(zhí)行到!"); } } } 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();// 針對當(dāng)前對象執(zhí)行喚醒所有線程的操作 System.out.println(Thread.currentThread().getName() + ":喚醒線程執(zhí)行成功!"); } } }
執(zhí)行結(jié)果為:
以上所述是小編給大家介紹的Java線程中的notifyAll喚醒操作,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對億速云網(wǎng)站的支持!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。