等待 与 唤醒
1、wait():让线程处于冻结状态,被wait的线程会被存储到线程池里
2、notify():唤醒线程池里任意一个线程
3、notifyAll():唤醒线程池里所有的线程。
这些方法都必须定义在同步中,因为这些方法是用于操作线程状态的方法,必须要明确到底操作的是那个锁上的线程
为什么操作线程的方法 wait notifh notifyAll 定义在Object类中,因为这些方法是监视器的方法,而监视器就是锁。
//这个是资源类 public class Resources { private String name; private String work; private boolean flag = false; public synchronized void set(String name,String work){ if(this.flag) try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } this.name = name; this.work = work; this.flag = true; this.notify(); } public synchronized void qu(){ if(!this.flag) try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("姓名:"+name+",工作:"+work); this.flag = false; this.notify(); } }
//这个事负责向资源类里存东西的,当资源类里有东西时候就等待,没有的时候就存
public class Input implements Runnable{ Resources r; public Input(Resources r){ this.r = r; } @Override public void run() { int num = 0; while (true){ if(num == 0){ r.set("张三","java"); }else { r.set("笑话","php"); } num = (num+1)%2; } } }
//这个是出东西的类,当没有时候就等待,有的时候就打印
public class Output implements Runnable{ Resources r; public Output(Resources r){ this.r = r; } @Override public void run() { while (true){ r.qu(); } } }
//测试函数
public class Test4 { public static void main(String[] args){ Resources r = new Resources(); Input i = new Input(r); Output o = new Output(r); Thread t = new Thread(i); Thread tt = new Thread(o); t.start(); tt.start(); } }