有人能提供一下简单的Java生产者消费者模型代码吗?

解决方案 »

  1.   

    public class TestThread { public static void main(String[] args) {
    Pool pool = new Pool();
    Thread t1 = new ThreadIn(pool);
    Thread t2 = new ThreadDe(pool);
    t2.start();
    t1.start(); }}class ThreadIn extends Thread {
    private Pool pool; public ThreadIn(Pool pool) {
    this.pool = pool;
    } public void run() {
    try {
    for (int i = 0; i < 10; i++) {
    pool.increase();
    } } catch (Exception e) { e.printStackTrace();
    }
    }
    }class ThreadDe extends Thread {
    private Pool pool; public ThreadDe(Pool pool) {
    this.pool = pool;
    } public void run() {
    try {
    for (int i = 0; i < 10; i++) {
    pool.decrease();
    } } catch (Exception e) { e.printStackTrace();
    } }
    }class Pool {
    private int num = 0; public synchronized void increase() throws Exception { while (num > 0) {
    this.wait();
    }
    num++;
    System.out.println("num:" + num);
    notify();
    } public synchronized void decrease() throws Exception { while (0 == num) {
    this.wait();
    }
    num--;
    System.out.println("num:" + num);
    notify();
    }
    }