我對併發感到困惑 - 我試圖阻止消費者線程運行,如果生產者已關閉,但如果消費者在take()上被阻塞時遇到問題。我曾嘗試使用布爾標誌添加一個posion藥丸,暫停當前線程,但仍無濟於事。併發問題 - 阻塞隊列
請有人可以幫助建議我去哪裏錯了。謝謝。
public class TestPoisonPill implements Runnable {
private BlockingQueue<String> queue = new ArrayBlockingQueue<String>(1);
private volatile boolean stopped = false;
public void addToQueue(String event) throws InterruptedException{
System.out.println("in add to queue");
if(event != null){
try {
queue.put(event);
} catch (InterruptedException e) {
stopped = true;
queue.put("Poison");
System.out.println("Unable to add the event to the queue, order routing processing is stopped");
throw e;
}
}
}
@Override
public void run() {
while(!stopped){
try {
if(queue.size() > 0){
String string = queue.take();
System.out.println("taken " + string + "from the queue");
}else{
continue;
}
}
catch (InterruptedException e) {
stopped = true;
}
}
}
public boolean isStopped(){
return stopped;
}
protected BlockingQueue<String> getQueue() {
return queue;
}
protected void setBoolean(boolean b){
this.stopped = b;
}
public static void main(String[] args) throws InterruptedException{
ExecutorService exec = Executors.newSingleThreadExecutor();
final TestPoisonPill t = new TestPoisonPill();
exec.execute(t);
ExecutorService exec2 = Executors.newSingleThreadExecutor();
Runnable addTask = new Runnable() {
public void run() {
while (true) {
try {
t.addToQueue("hi");
Thread.sleep(100);
} catch (InterruptedException ex) {
System.out.println("add task interrupted ");
t.setBoolean(true);
break;
}
}
}
};
exec2.execute(addTask);
Thread.sleep(1000);
exec2.shutdownNow();
}
}
你好我正在使用一箇中毒丸,我刪除,因爲它沒有工作!我不明白的是 - 爲什麼兩個執行者都需要關閉,因爲run方法肯定應該退出? – Biscuit128
只需添加一些示例代碼@Bincuit128。 – Gray
對不起@餅乾128,我沒有看到你的問題。在將最後一項任務提交給執行程序服務後,您需要關閉該程序。否則,它會永遠等待,看看是否要提交更多任務。 'shutdown()'只停止正在運行的新任務 - 它允許現有任務運行直到完成。 'shutdownNow()'刪除所有等待中的任務並中斷正在運行的任務。 – Gray