spring線程池ThreadPoolExecutor配置並且得到任務執行的結果_Spring

來源:互聯網
上載者:User

用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;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.