java 執行緒間的通知和掛起處理 (wait/notify)
阿新 • • 發佈:2019-02-03
public class ThreadWaitNotifyTest{ private boolean flag = true; private void test(){ Object lock = new Object(); Thread t = new Thread(new Runnable() { @Override public void run() { synchronized (lock) { for(;flag;){ log("threadid = "+ Thread.currentThread().getId()); try { lock.wait(); log("threadid wait end"); } catch (InterruptedException e) { e.printStackTrace(); } } log("threadid end thread"); } } }); t.start(); for(int i=0; i < 3; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } log("threadid notify " + i); synchronized(lock) { lock.notify(); } } synchronized (lock) { flag = false; lock.notify(); } } }