生产者消费者问题
代码:
package face_duixiang_first; public class Test { public static void main(String[] args) { Clerk clerk = new Clerk(); Thread productorthread = new Thread(new Productor(clerk)); Thread consumerthread = new Thread(new Consumer(clerk)); productorthread.start(); consumerthread.start(); Thread productorthread2 = new Thread(new Productor(clerk)); Thread consumerthread2 = new Thread(new Consumer(clerk)); productorthread2.start(); consumerthread2.start(); } } //售货员类 class Clerk{ private int product = 0; public synchronized void addProduct() { if(product >= 20) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } else { product++; System.out.println("生产者正在生产第" + product + "件产品"); notifyAll(); } } public synchronized void getProduct() { if(this.product <= 0) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } else { System.out.println("消费者正在消费第" + product + "件产品"); product--; notifyAll(); } } } //生产者 class Productor implements Runnable{ Clerk clerk; public Productor(Clerk clerk) { super(); this.clerk = clerk; } @Override public void run() { while(true) { System.out.println("生产者开始生产产品"); try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } clerk.addProduct(); } } } // 消费者 class Consumer implements Runnable{ Clerk clerk; public Consumer(Clerk clerk) { this.clerk = clerk; } @Override public void run() { System.out.println("消费者开始取走产品"); while(true) { try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } clerk.getProduct(); } } }