-2

以下源代码用于实现产品/消费者模式,但效果不佳,不知道如何解决。

第一类:生产者

package test;

import java.util.ArrayList;
import java.util.List;

public class Productor extends Thread {

private List list = null;

public Productor(ArrayList list) {
    this.list = list;
}

public synchronized void product() throws InterruptedException {
    for (int e = 0; e < 10; e++) {
        System.out.println("Add-" + e + "  " + System.currentTimeMillis());
        list.add(e);

        if (list.size() >= 10) {
            wait();
        } else {
            notifyAll();
        }
    }
}

public void run() {
    try {
        while(true){
            product();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

2类:消费包测试;

import java.util.ArrayList;
import java.util.List;

public class Consumer extends Thread {

private List list = null;

public Consumer(ArrayList list) {
    this.list = list;
}

public synchronized void consume() throws InterruptedException {
    if (list.size() <= 0) {
        wait();
    } else {
        notifyAll();
    }

    for (int e = 0; e < list.size(); e++) {
        System.out.println("Remove-" + e + "  "
                + System.currentTimeMillis());
        list.remove(e);
    }
}

public void run() {
    try {
        while(true){
            consume();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

第3类:产品/消费者包装测试的测试;

import java.util.ArrayList;

public class TestCP {
public static void main(String args[]) throws InterruptedException {
    ArrayList product = new ArrayList();
    Productor pt = new Productor(product);
    Consumer ct = new Consumer(product);
    pt.start();
    ct.start();
}
}

TestCP 的输出是:

加0 1340777963967

加1 1340777963968

加2 1340777963968

加3 1340777963968

加4 1340777963968

加5 1340777963968

加6 1340777963968

加7 1340777963968

加8 1340777963968

加9 1340777963968

我的意图是 Productor 产品 10 个元素存储在列表中并由消费者消费,然后 Productor 产品元素再次,消费者再次消费......任何反馈将不胜感激,谢谢。

4

1 回答 1

0

You wait/notify on the diferent thread not on the list. So the threads are running on their own monitors not on a shared one. Search for "java wait notify" and keep on reading.

于 2012-06-27T06:55:11.120 回答