日期:2014-05-20 浏览次数:20788 次
public class Wait { public static void main(String[] args) { Queue q = new Queue(); Producer pro = new Producer(q); Consumer con = new Consumer(q); pro.start(); con.start(); } } class Queue { int value; boolean full = false; public synchronized void input(int i) { if (!full) { value = i; full = true; notify(); } else { try { wait(); } catch (Exception e) { e.printStackTrace(); } } } public synchronized int output() { if (!full) { try { wait(); } catch (Exception e) { e.printStackTrace(); } } else { full = false; notify(); } return value; } } class Producer extends Thread { Queue q; Producer(Queue q) { this.q = q; } public void run() { for (int i = 0; i < 10; i++) { synchronized (this) { while (q.full == true); q.input(i); System.out.println("Producer input " + i); } } } } class Consumer extends Thread { Queue q; Consumer(Queue q) { this.q = q; } public void run() { while (true) { synchronized (this) { while (q.full == false) ; int temp = q.output();//这里顺便将值保存起来,以便退出这个线程,否则你的CPU很生气 System.out.println("Consumer get " + temp); if(temp >=9) System.exit(0); } } } }