0
這裏的時候拒絕是我的代碼:得到錯誤FutureTask @ 2c7b84de使用線程池
class Processor implements Runnable {
private int id;
private Integer interaction;
private Set<Integer> subset;
private static volatile AtomicBoolean notRemoved = new AtomicBoolean(true);
public Object<E> dcp;
public Iterator<Integer> iterator;
public Processor(int id, Integer interaction, Set<Integer> subset, Object<E> dcp, Iterator<Integer> iterator) {
this.id = id;
this.interaction = interaction;
this.subset= subset;
this.dcp = dcp;
this.iterator = iterator;
}
public void run() {
while (Processor.notRemoved.get()){
System.out.println("Starting: " + this.id);
if (this.dcp.PA.contains(this.interaction)){
this.subset.add(this.interaction);
this.dcp.increaseScore(this.subset);
if (!this.subset.contains(this.interaction) && Processor.notRemoved.get()){
Processor.notRemoved.set(false);
iterator.remove();
}
}
System.out.println("Completed: " + this.id);
}
}
}
public class ConcurrentApp {
public void mainFunction (Object<E> dcp, int threads) {
ExecutorService executor = Executors.newFixedThreadPool(threads);
int i =1;
while ((dcp.PA.size() > i) && (i <= dcp.R)){
for (Iterator<Integer> iterator = dcp.PA.iterator(); iterator.hasNext();){
Integer interaction = iterator.next();
ArrayList<Integer> removed = new ArrayList<Integer>(dcp.PA);
removed.remove(interaction);
ArrayList<Set<Integer>> subsets = dcp.getSubsets(removed, i);
for (int j = 0; j< subsets.size(); j++){
executor.submit(new Processor(j, interaction, subsets.get(j), dcp, iterator));
}
executor.shutdown();
System.out.println("All tasks submitted");
try {
executor.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
System.out.println("HERE");
e.printStackTrace();
}
}
System.out.println("All tasks completed");
i++;
}
}
}
當我在ConcurrentApp運行mainFunction,我得到以下錯誤: 異常線程「main」的java.util.concurrent .RejectedExecutionException:任務[email protected]拒絕自[email protected] [已終止,池大小= 0,活動線程數= 0,排隊任務數= 0,已完成任務數= 8]
我知道這是因爲我沒有使用執行tor.shutdown()正確,但我不知道爲什麼?
編輯:我打印時,每個線程啓動並完成其任務。這裏是控制檯輸出:
Starting: 1
Starting: 2
All tasks submitted
Starting: 0
Completed: 2
Completed: 1
Completed: 0
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task [email protected] rejected from [email protected][Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 8]
這至少表明線程池中的3個線程在錯誤消失之前完成了他們的任務。
「volatile AtomicBoolean」不是必需的。使用其中一個或另一個 – efekctive
@efekctive OH YEAH!感謝收穫。我忘了AtomicBoolean已經是volatile了。 –
你會嘗試以下操作:切換提交執行? – efekctive