1. 程式人生 > 實用技巧 >Callable和Future結合線程池使用

Callable和Future結合線程池使用

package com.leelen.esafe.test;

import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class ThreadPoolBuilderTest {
    // 建立執行緒池
    private static ExecutorService pool = new ThreadPoolExecutor(2, 4, 3000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(1000), Executors.defaultThreadFactory(), new
ThreadPoolExecutor.AbortPolicy()); @Test public void testThread1() { System.out.println("---start---"); // 模擬20個併發 int num = 20; List<MyTask> myTasks = new ArrayList<>(); for (int i = 0; i < num; i++) { MyTask myTask = new MyTask(i); myTasks.add(myTask); }
// 執行任務 List<Future<Integer>> futures = new ArrayList<>(); try { for (int i = 0; i < myTasks.size(); i++) { // 執行緒執行返回結果 Future<Integer> future = pool.submit(myTasks.get(i)); futures.add(future); } }
catch (Exception e) { } // 輸出執行緒執行結果 try { for (int i = 0; i < futures.size(); i++) { Future<Integer> future = futures.get(i); Integer result = future.get(); System.out.println(result); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } System.out.println("---end---"); } // Callable執行緒任務 class MyTask implements Callable<Integer> { Integer tid; public MyTask(Integer tid) { this.tid = tid; } @Override public Integer call() throws Exception { System.out.println("this thread id is = " + tid); Thread.sleep(3000); return tid; } } }