綫程通信
- wait():令當前綫程挂起,並釋放CPU資源,釋放鎖,而當前綫程則進入到綫程等待隊列
- notify()/notifyAll():喚醒正在等待的綫程中,優先級最高的(所有的)綫程結束等待
- 功能:數據遞加,綫程“甲”、“乙”交替執行,輸出數據 以上這些代碼必須寫在同步代碼塊中,否則報錯
代码示例
public class Test7 { public static void main(String[] args) { PrintNum pn = new PrintNum(); Thread t = new Thread(pn); Thread t1 = new Thread(pn); t.setName("甲"); t1.setName("乙"); t.start(); t1.start(); }}class PrintNum implements Runnable{ int num = 1; @Override public void run() { while(true){ synchronized (this) { notify(); //喚醒等待隊列中的綫程 if (num <= 20) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ":" + (num++)); } else { break; } try { wait();//數據加一,輸出之后,此綫程挂起 } catch (InterruptedException e) { e.printStackTrace(); } } } }}