go4it

just do it

模式5-Producer-Consumer

参考《java多线程设计模式》

在多个生产者和多个消费者之间加入一个中间者来缓冲线程之间的处理速度差。

// 放置蛋糕
    public synchronized void put(String cake) throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + " puts " + cake);
        while (count >= buffer.length) {
            wait();
        }
        buffer[tail] = cake;
        tail = (tail + 1) % buffer.length;
        count++;
        notifyAll();
    }
    // 取得蛋糕
    public synchronized String take() throws InterruptedException {
        while (count <= 0) {
            wait();
        }
        String cake = buffer[head];
        head = (head + 1) % buffer.length;
        count--;
        notifyAll();
        System.out.println(Thread.currentThread().getName() + " takes " + cake);
        return cake;
    }

posted on 2009-05-08 22:45  cxccbv  阅读(297)  评论(0)    收藏  举报

导航