1、notify()、wait()、和notifyAll()方法是由object类实现的因此这几个方法是所有对象的一部分
wait()使线程等待直到有notify()
2、基本形式:
final void wait() throws InterruptedException //等待直到被通知
final void wait(long millis) throws InterruptedException //等待直到被通知或者直到经过以毫秒为单位指定的millis 周期
final void wait(long millis,int nanos) throws InterruptedException //以纳秒为单位指定等待周期
final void notify() //恢复一个等待中的线程
final void notifyAll()// 通知所有的线程 然后具有最高优先级的获得资源
class TickTock { String state;//设置标志 "Tick" or "Tock" synchronized void tick(boolean running){ if(!running){//stop the clock state = "ticked"; notify(); //notify any waiting thread return ; } System.out.print("Tick"); //let tock() run tick()通知tock(); try { state = "ticked"; Thread.sleep(500); notify(); while (!state.equals("tocked")) { wait();//wait for tock() to complete tick()等待tock(); } } catch (InterruptedException exc) { System.out.println("Thread interrupted!"); } } synchronized void tock(boolean running){ if(!running){ state = "tocked"; notify(); //notify any waiting thread return ; } System.out.println("Tock"); try { state = "tocked"; Thread.sleep(500); notify();//let tock() run while (!state.equals("ticked")) { wait();//wait for tick() to complete } } catch (InterruptedException exc) { System.out.println("Thread interrupted!"); } } } class MyThread implements Runnable { Thread thrd; TickTock ttob; MyThread(String name,TickTock tt){ thrd = new Thread(this,name); ttob = tt; thrd.start();//start the thread } public void run(){ if (thrd.getName().compareTo("Tick") == 0) { for (int i=0; i<5 ; i++ ) { ttob.tick(true); } ttob.tick(false); } else { for (int i=0; i<5 ; i++ ) { ttob.tock(true); } ttob.tock(false); } } } class ThreadCom { public static void main(String[] args) { TickTock tt = new TickTock(); MyThread mt1 = new MyThread("Tick",tt); MyThread mt2 = new MyThread("Tock",tt); try { mt1.thrd.join(); mt2.thrd.join(); } catch (InterruptedException exc) { System.out.println("异常中断!"); } System.out.println("主线程停止"); } } //当执行Tick()时,显示单词Tick 并且把state设置为"Ticked",然后调用modify()之后通知其他线程 //然后调用了wait()使得自己挂起。直到tock()调用notify()并且把自己挂起