日期:2014-05-20 浏览次数:20694 次
class Producter extends Thread { Queue q; Producter (Queue q) { this.q=q; } public void run() { for(int i=0;i<10;i++) { q.put(i); System.out.println("producter :"+i); } } } class Consumer extends Thread { Queue q; Consumer(Queue q) { this.q=q; } public void run() { while(true) { System.out.println("Consumer:"+q.get()); } } } class Queue //key { int value; boolean bFull=false; public synchronized void put(int i) { if(!bFull) { value=i; bFull=true; notify();//必须用在synchronized } try { wait();//必须捕获异常 // 等待消费者取走数据 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized int get() { if(!bFull) try { wait(); // 等待生产者写入数据 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } bFull=false; // 通知生产者数据已经被取走,可以再次写入数据 notify(); return value; } } public class test //测试类 { public static void main(String[] args) { Queue q=new Queue(); Producter p=new Producter(q); Consumer c=new Consumer(q); p.start(); c.start(); } } 问题补充:System.out.println("Consumer:"+q.get()); } } } class Queue //key { int value; boolean bFull=false; public synchronized void put(int i) { if(!bFull) { value=i; bFull=true; notify();//必须用在synchronized } try { wait();//必须捕获异常 // 等待消费者取走数据 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized int get() { if(!bFull) try { wait(); // 等待生产者写入数据 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } bFull=false; // 通知生产者数据已经被取走,可以再次写入数据 notify(); return value; } } public class test //测试类 { public static void main(String[] args) { Queue q=new Queue(); Producter p=new Producter(q); Consumer c=new Consumer(q); p.start(); c.start(); } }