package com.kk.thread; public class Test { public static void main(String[] args) { Queue q=new Queue(); Producer p=new Producer(q); Consumer c=new Consumer(q); c.start(); p.start(); } } class Producer extends Thread { Queue q; public Producer(Queue q) { this.q=q; } public void run() { for (int i = 0; i < 10; i++) { q.put(i); System.out.println("q.put(i)=="+i); } } } class Consumer extends Thread { Queue q; public Consumer(Queue q) { this.q=q; } public void run() { while(true) System.out.println("q.get(i)=="+q.get()); } } class Queue { int i; boolean bFull; public synchronized void put(int i) { if(!bFull){ //如果队列里面没有值 this.i = i; //给队列添加值 bFull=true; //设置为有值 notify(); //唤醒等待队列 } try { wait(); //无论有没有进入if ,此时bFull为true,表示有值,则线程等待,让Consumer取。 } catch (InterruptedException e) { e.printStackTrace(); } } public synchronized int get() { if(!bFull){ //如果bFull没有值 try { wait();//则让线程等待,让Producer放入值 } catch (InterruptedException e) { e.printStackTrace(); } } notify(); //此时表示bFull里面有值,要唤醒Pruducer继续放入值 bFull=false; //设置bFull为没有值,因为后面将会取走i的值 return i; } }