用ThreadPoolExecutor的時候,又想知道被執行的任務的執行情況,這時就可以用FutureTask。
原創不易,轉載請註明出處:spring線程池ThreadPoolExecutor配置並且得到任務執行的結果
代碼下載地址:http://www.zuidaima.com/share/1724478138158080.htm
ThreadPoolTask 01 package com.zuidaima.threadpool; 02 03 import java.io.Serializable; 04 import java.util.concurrent.Callable; 05 06 public class ThreadPoolTask implements Callable<String>, Serializable { 07 08 private static final long serialVersionUID = 0; 09 10 // 儲存任務所需要的資料 11 private Object threadPoolTaskData; 12 13 private static int consumeTaskSleepTime = 2000; 14 15 public ThreadPoolTask(Object tasks) { 16 this.threadPoolTaskData = tasks; 17 } 18 19 public synchronized String call() throws Exception { 20 // 處理一個任務,這裡的處理方式太簡單了,僅僅是一個列印語句 21 System.out.println("開始執行任務:" + threadPoolTaskData); 22 String result = ""; 23 // //便於觀察,等待一段時間 24 try { 25 // long r = 5/0; 26 for (int i = 0; i < 100000000; i++) { 27 28 } 29 result = "OK"; 30 } catch (Exception e) { 31 e.printStackTrace(); 32 result = "ERROR"; 33 } 34 threadPoolTaskData = null; 35 return result; 36 } 37 }
類比用戶端提交的線程 01 package com.zuidaima.threadpool; 02 03 import java.util.concurrent.ExecutionException; 04 import java.util.concurrent.FutureTask; 05 import java.util.concurrent.TimeUnit; 06 07 import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; 08 09 public class StartTaskThread implements Runnable { 10 11 private ThreadPoolTaskExecutor threadPoolTaskExecutor; 12 private int i; 13 14 public StartTaskThread(ThreadPoolTaskExecutor threadPoolTaskExecutor, int i) { 15 this.threadPoolTaskExecutor = threadPoolTaskExecutor; 16 this.i = i; 17 } 18 19 @Override 20 public synchronized void run() { 21 String task = "task@ " + i;