生产者
/** * 类说明:生产者 * * @author 作者: user * @version 创建时间:2011-4-5 下午01:48:11 */ public class Producer implements Runnable { private SyncStack ss; private int num; private static int counter = 1; public Producer(SyncStack ss) { this.ss = ss; num = counter++; } @Override public void run() { char c; for (int i = 0; i < 10; i++) { c = (char) (Math.random() * 26 + 'A'); ss.push(c);//向堆栈中添加数据 System.out.println("生产者 " + num + ": " + c); try { Thread.sleep((int) (Math.random() * 300)); } catch (InterruptedException e) { e.printStackTrace(); } } } }
消费者
/** * 类说明:消费者 * * @author 作者: user * @version 创建时间:2011-4-5 下午01:56:18 */ public class Consumer implements Runnable { private SyncStack ss;//堆栈对象 private int num; private static int counter = 1; public Consumer(SyncStack ss) { this.ss = ss; num = counter++; } @Override public void run() { char c; for (int i = 0; i < 10; i++) { c = ss.pop();//从堆栈中取数据 System.out.println("消费者 " + num + ": " + c); try { Thread.sleep((int) (Math.random() * 200)); } catch (InterruptedException e) { e.printStackTrace(); } } } }
堆栈类
import java.util.ArrayList; import java.util.List; /** * 类说明:堆栈类 * * @author 作者: user * @version 创建时间:2011-4-5 下午01:17:48 */ public class SyncStack { private List<Character> buffer = new ArrayList<Character>(); public SyncStack() { } // 堆栈取数据 public synchronized char pop() { char c; if (buffer.size() == 0) { try { System.out.println(Thread.currentThread().getName() + " 正在等待 ……………………"); this.wait();// 如果堆栈中没有数据 则线程等待 } catch (Exception e) { e.printStackTrace(); } } c = ((Character) buffer.get(buffer.size() - 1)).charValue(); buffer.remove(buffer.size() - 1); return c; } // 向堆栈中添加数据 public synchronized void push(char c) { this.notify();// 唤醒在此对象监视器上等待的单个线程 Character ch = new Character(c); buffer.add(ch); } }
主方法
/** * 类说明: * * @author 作者: user * @version 创建时间:2011-4-5 下午01:59:54 */ public class Main { /** * @param args */ public static void main(String[] args) { SyncStack ss = new SyncStack(); //生产者p Producer p = new Producer(ss); Thread t1 = new Thread(p); t1.start(); //生产者p2 Producer p2 = new Producer(ss); Thread t3 = new Thread(p2); t3.start(); //消费者1 Consumer c = new Consumer(ss); Thread t2 = new Thread(c); t2.setName("消费者1 "); t2.start(); //消费者1 Consumer c2 = new Consumer(ss); Thread t4 = new Thread(c2); t4.setName("消费者2 "); t4.start(); } }