生产者-消费者
1.需求:生产者生产奶=》奶箱=》消费者消费
2.帮助类
1)BOX(奶箱)
package shapes; public class Box{ private int milk; private boolean state = false; public synchronized void put(int milk) { // 如果没有则等待 if(state) { try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 有的话则生产 this.milk = milk; System.out.println("送牛奶" + this.milk + "瓶放入奶箱。"); state = true; //唤醒其它等待的线程 notifyAll(); } public synchronized void get() { // 如果没有,则等待生产 if(!state) { try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 如果有,则消费 System.out.println("用户拿到第" + this.milk + "瓶奶。"); state = false; //唤醒其它等待的线程 notifyAll(); } }
2)生产者
package shapes; public class Product implements Runnable { private Box b; public Product(Box b) { this.b = b; } @Override public void run() { for(int i = 1; i <= 5; i++) { b.put(i); } } }
3)消费者
package shapes; public class Customer implements Runnable { private Box b; public Customer(Box b) { this.b = b; } @Override public void run() { while(true) { b.get(); } } }
4)运行主代码
package shapes; public class Main { public static void main(String[] args) { //创建箱子 Box b = new Box(); //创建生产者 Product p = new Product(b); //创建消费者 Customer c= new Customer(b); Thread t1 = new Thread(p); Thread t2 = new Thread(c); //启动 t1.start(); t2.start(); } }
3.结果
参阅:https://www.bilibili.com/video/BV1vk4y117fU?p=340