我在学习多线程的生产者-消费者模式。其基本思想是一个生产者线程将数据放入阻塞队列,然后许多消费者线程将从队列中获取数据。
使用者的“run()”方法如下所示。
@Override
public void run() {
List<String> record;
while(true) {
if(this.channel.getState()) {
break;
}
try {
// System.out.println(this.channel.getSharedQueue().size());
record = this.channel.getSharedQueue().take();
...
} catch (InterruptedException e) {
e.printStackTrace();
}
}
record = null;
}
当我注解掉“system.out.println(…)”时,整个程序都会卡住。但是,如果添加“system.out.println(…)”,程序将平稳运行。有人能解释一下“system.out.println(…)”背后的魔力吗?
下面是生产者的“run()”方法。
public void run() {
...
while ((line = br.readLine()) != null && line.length() > 1) {
List<String> record = parseRow(line);
if(record != null)
this.channel.getSharedQueue().put(record);
}
...
this.channel.setState(true);
}
以及主要的方法。
ExecutorService producerExecutor = Executors.newSingleThreadExecutor();
Runnable producer = new Producer(channel, ...);
producerExecutor.execute(producer);
ExecutorService consumerExecutor = Executors.newFixedThreadPool(30);
for(int i = 0; i < 30; i++) {
Runnable consumer = new Consumer(channel);
consumerExecutor.execute(consumer);
}
consumerExecutor.shutdown();
producerExecutor.shutdown();
while (!consumerExecutor.isTerminated() || !producerExecutor.isTerminated());
channel类就像
public class Channel {
private volatile boolean state;
...
public boolean getState() {
return this.state;
}
public void setState(boolean state) {
this.state = state;
}
...
}
谢谢你的帮助!
暂无答案!
目前还没有任何答案,快来回答吧!