public class ProducerConsumer { public static void main(String[] args) { BigLetter bigLetter = new BigLetter(); Producer prod = new Producer(bigLetter); Consumer consu = new Consumer(bigLetter); Thread p = new Thread(prod); Thread c = new Thread(consu); p.start(); c.start(); } } /** * 同步共享资源类 * */ class BigLetter { int index = 0; char[] ch = new char[10]; public synchronized void prod(char c) { while(index == ch.length)//当字符数组大小和index相等,生产者等待 { try { this.wait(); } catch (Exception e) { // TODO: handle exception } } this.notifyAll(); ch[index] = c; index++; } public synchronized char consu() { while(index == 0)//当index为0,说明字符数组为空,消费者等待 { try { this.wait(); } catch (Exception e) { // TODO: handle exception } } this.notifyAll(); index--; return ch[index]; } } /** * 生产者类 * */ class Producer implements Runnable { BigLetter bigLetter = new BigLetter(); Producer(BigLetter bigLetter) { this.bigLetter = bigLetter; } public void run() { for(int i = 0;i<20;i++) { char c = (char)(Math.random()*26+'A'); bigLetter.prod(c); System.out.println("生产者生产了:"+ c ); } } } /** * 消费者类 * */ class Consumer implements Runnable { BigLetter bigLetter = new BigLetter(); Consumer(BigLetter bigLetter) { this.bigLetter = bigLetter; } public void run() { for(int i = 0;i<20;i++) { char c = bigLetter.consu(); System.out.println("消费者消费了:"+ c ); } } }