【发布时间】:2015-05-21 04:32:03
【问题描述】:
com.offbynull.coroutines 版本 1.1.0 消费者只消费 7500 条消息。
请帮助我理解为什么这段代码只使用7500 消息而不是30000。
public class DemoProducerConsumer {
public static int cnt = 0;
public static final int MAX = 10000;
public static class Producer implements Coroutine {
@Override
public void run(Continuation ctn) throws Exception {
String thName = Thread.currentThread().getName();
System.out.println(thName + ") Producer starting...");
Consumer consumer = new Consumer();
for (int i = 0; i < 3; i++) {
consumer.consume(ctn, "Hello:" + i);
}
System.out.println(thName + ") Producer published 3 messages");
}
}
public static class Consumer {
public void consume(Continuation ctn, String message) {
String thName = Thread.currentThread().getName();
System.out.println(thName + ")" + message);
cnt++; // <<< SUSPECT bug here.
ctn.suspend(); // <<< SUSPECT bug here.
}
}
public static final void main(String... args) throws InterruptedException {
String thName = Thread.currentThread().getName();
System.err.println(thName + ") Preparing Producer ");
new Thread(new Runnable() {
public void run() {
cnt = 0;
Producer producer = new Producer();
CoroutineRunner runner = new CoroutineRunner(producer);
for (int i = 0; i < MAX; i++) {
runner.execute();
}
System.out.println(thName + ") Producer Looped " + MAX + " times.");
}
}).start();
System.err.println(thName + ") Waiting " + (MAX * 3) + " message to be consumed...");
Thread.sleep(10000);
System.err.println(thName + ") Message consumed:" + cnt);
System.err.println(thName + ") Exiting...");
}
}
我计划将它与Thread Pool 一起使用以实现更高性能的 MVC 服务器。
消费者和生产者的分离是必须的。
【问题讨论】:
标签: java coroutine java-threads