2015-01-16 20 views
1

在我的應用程序中,我使用了一個自定義ThreadPoolExecutor,它可以通過擴展ThreadPoolExecutor類來暫停和恢復Executor。我希望在執行ExecutorService的關閉方法後執行重啓功能。我第一次嘗試創建ThreadPoolExecutor的新實例並失敗。我發現this question,並嘗試ExecutorCompletionService,導致相同的故障,它沒有按預期執行。如何在關機後重用ThreadPoolExecutor

第一次當我點擊我的用戶界面中的開始按鈕它執行得很好,並在完成後,當我再次啓動時,它不會給我預期的結果。相反,會給我第一次運行的前一個結果。什麼是我能夠完成這個任務的最合適的方式? 在此先感謝:)

以下行將在每次按鈕單擊時執行。

private static int jobs = 10; 
    ExecutorService executor = new PausableThreadPoolExecutor(num_threads, num_threads, 5000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(jobs)); 
    for (int i = 0; i < jobs; i++) { 
     Runnable worker = new TaskToDo(jobs); 
     executor.submit(worker); 
    } 

    executor.shutdown(); 
    while (!executor.isTerminated()) {} 
    System.out.println("Finished all threads"); 

This是我曾經有暫停/恢復實施的來源。

+0

顯示一些代碼。 – kosa

+0

請顯示一些代碼,並描述什麼是「預期的結果」 –

+0

但我不明白這是什麼問題?你有沒有設法讓你的暫停/恢復executorService? 關閉後重新啓動executorService違反了executorService規範,因此您不應該嘗試執行此操作。如果你嘗試這樣做來解決你的暫停/恢復問題,這是不是好的方式去 –

回答

0

也許的ScheduledThreadPoolExecutor您使用此方法可以返回的ScheduledFuture ScheduledFuture或未來Future持有引用到任務可以重新啓動它ScheduledThreadPoolExecutor

ScheduledFuture now = null; 
ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1); 
Runnable runner = new Runnable(){ 
       public void run() 
       { 
        rollthedice(); //your method or runnable of choice 
       } 
      }; 

啓動和重啓類似「那裏有其他的方法太「

now = scheduler.scheduleAtFixedRate(runner, 0, 250, TimeUnit.MILLISECONDS); 

取消或停止

now.cancel(true); 
now = null; 
+0

您建議的重新啓動將以不同的方式工作。這將在每250毫秒開始。我對麼..??? – charagaila

+0

是的,你應該使用Future和方法scheduler.submit(Runnable任務),而不是ScheduledFuture和scheduleatfixedrate,我沒有一個例子,我剛纔看到你把你的代碼放到了,文檔的鏈接就在那裏 – JRowan

相關問題