生产者消费者问题
仓库有6个放苹果的盒子,需要放苹果进去,当放满以后不能再放了需要等消费者拿苹果,如果仓库里面苹果为空,消费者就不能再拿苹果了,需要等生产者生产苹果放进去才可以取。

(1) 苹果
public class AppleBox { int id; public AppleBox(int id) { super(); this.id = id; } @Override public String toString() { return "AppleBox [id=" + id + "]"; } }
(2) 仓库
public class SyncStack { int index=0; AppleBox[] arrBox=new AppleBox[6]; public synchronized void push(AppleBox apple) { while (index==arrBox.length-1) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } arrBox[index]=apple; index++; this.notifyAll(); } public synchronized AppleBox pop() { while (index==0) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } index--; this.notifyAll(); return arrBox[index]; } }
(3) 生产者
public class Producer implements Runnable { SyncStack ss=null; public Producer(SyncStack ss) { super(); this.ss = ss; } @Override public void run() { // TODO Auto-generated method stub for (int i=0;i<30;i++) { AppleBox apple=new AppleBox(i); ss.push(apple); System.out.println("生产者生产了苹果"+apple.toString()); try { Thread.sleep((int)Math.random()*1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
(4) 消费者
public class Consumer implements Runnable { SyncStack ss=null; public Consumer(SyncStack ss) { super(); this.ss = ss; } @Override public void run() { // TODO Auto-generated method stub for (int i=0;i<30;i++) { AppleBox apple=ss.pop(); System.out.println("消费了"+apple.toString()); try { Thread.sleep((int)Math.random()*3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
主程序:
public class TestThread { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub SyncStack ss=new SyncStack(); Producer p=new Producer(ss); //Consumer c=new Consumer(ss); new Thread(p).start(); //new Thread(p).start(); //new Thread(p).start(); //new Thread(p).start(); //new Thread(p).start(); //new Thread(c).start(); } }
 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号