Sleep 和 wait
sleep不会释放锁,而wait会释放锁; 使用区域不用,sleep是哪都能用,wait只能在同步方法或者同步代码块中。
sleep是Thread调用的, 而wait和notify方法必须是“锁对象”调用的!!
生产者 和 消费者
//实体类 public class Baozi { String pi; String xian; boolean flag = false; } //主测试类 public class BaoziMain { public static void main(String[] args) { Baozi bz = new Baozi(); BaoziPu bzp = new BaoziPu(bz); bzp.start(); ChiHuo ch = new ChiHuo(bz); ch.start(); } }
生产者
public class BaoziPu extends Thread { private Baozi bz; public BaoziPu(Baozi bz){ this.bz = bz; } @Override public void run() { while (true){ synchronized (bz){ if(bz.flag == true){ //包子铺进入等待的状态 等待客人吃完包子 try { bz.wait(); //注意必须是锁对象来调用wait方法!!!!!! } catch (InterruptedException e) { e.printStackTrace(); } } //被唤醒后执行 System.out.println("正在生产包子....."); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } bz.flag = true; System.out.println("赶紧来吃包子吧"); bz.notify(); } } } }
消费者
public class ChiHuo extends Thread { private Baozi bz; public ChiHuo(Baozi bz) { this.bz = bz; } @Override public void run() { while (true){ synchronized (bz){ if(bz.flag == false){ try { bz.wait(); //注意必须是锁对象来调用wait方法!!!!!! } catch (InterruptedException e) { e.printStackTrace(); } } //被唤醒后执行 System.out.println("吃货正在吃包子....."); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } bz.flag = false; System.out.println("赶紧做包子吧"); bz.notify(); } } } }