2011-07-03 118 views
1

public void execute(Runnable command)從訪問提交對象的ThreadPoolExecutor

此命令對象包含提交對象內,但它似乎已換。

如何從自定義線程池執行程序中訪問提交的對象?或者,從ThreadPoolExecutor的before/after/execute方法中嘗試訪問提交的對象是不是一個好主意?

回答

4

請勿使用execute,請使用submit,它會返回Future,它是任務的句柄。下面是一些示例代碼:

ExecutorService service = Executors.newCachedThreadPool(); 

Callable<String> task = new Callable<String>() { 
    public String call() throws Exception { 
     return "hello world"; 
    } 
}; 

Future<String> future = service.submit(task); 

雖然你不能直接訪問任務,你仍然可以與它進行交互:

future.cancel(); // Won't start task if not already started 
String result = future.get(); // blocks until thread has finished calling task.call() and returns result 
future.isDone(); // true if complete 

您還可以通過該服務進行交互:

service.shutdown(); //etc  

編輯公司意見:

如果你wan噸做一些記錄,使用anonymous class重寫afterExecute()方法,是這樣的:

ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1)) { 
     @Override 
     protected void afterExecute(Runnable r, Throwable t) 
     { 
      // Do some logging here 
      super.afterExecute(r, t); 
     } 
    }; 

覆蓋其它方法需要。

快速插件:恕我直言,這個主題的聖經是Java Concurrency in Practice - 我建議你買它並閱讀它。

+0

謝謝,我已經在使用提交(Runnable任務,V結果)調用,它將返回一個未來。我正在嘗試在threadpoolexecutor中執行一些日誌記錄,特別是剛剛完成的任務,只是爲了幫助進行調試。另一個選擇是對未來的對象進行阻塞get(),但是對於這樣一個簡單的任務,特別是當我看到afterExecute()方法時,這看起來像對我進行輪詢,這告訴我有些任務剛剛完成。 –

+0

請參閱編輯答案。希望有幫助。 – Bohemian