概述
Callable介紹見:http://blog.csdn.net/zengmingen/article/details/53288119
多線程介紹見:http://blog.csdn.net/zengmingen/article/details/53284999
代碼
package multithreading.pool;import java.util.concurrent.Callable;public class TaskCallable implements Callable<String>{/**線程編號*/private int tNo;public TaskCallable(int tNo){this.tNo=tNo;}@Overridepublic String call() throws Exception {String tName=Thread.currentThread().getName();long currentTimeMillis = System.currentTimeMillis();System.out.println(tNo+"-"+tName+" start time is:"+currentTimeMillis/1000);try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(tNo+"-"+tName+ " is working...");return "the thread is "+tNo;}}
TestPool.java
package multithreading.pool;import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;public class TestPool {public static void main(String[] args) throws Exception, ExecutionException {List<Future<String>> futures = new ArrayList<Future<String>>();ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(2);for (int i = 0; i < 5; i++) {Future<String> future = newFixedThreadPool.submit(new TaskCallable(i));futures.add(future);}// 打印結果for (Future<String> f : futures) {boolean done = f.isDone();// 從結果的打印順序可以看到,即使未完成,也會阻塞等待System.out.println(done ? "已完成" : "未完成");//從Future中get結果,這個方法是會被阻塞的,一直要等到線程任務返回結果System.out.println("已完成線程返回future結果: " + f.get());}newFixedThreadPool.shutdown();}}
運行結果
0-pool-1-thread-1 start time is:1479808023
未完成
1-pool-1-thread-2 start time is:1479808023
0-pool-1-thread-1 is working...
1-pool-1-thread-2 is working...
已完成線程返回future結果: the thread is 0
已完成
已完成線程返回future結果: the thread is 1
未完成
2-pool-1-thread-1 start time is:1479808024
3-pool-1-thread-2 start time is:1479808024
3-pool-1-thread-2 is working...
2-pool-1-thread-1 is working...
4-pool-1-thread-2 start time is:1479808026
已完成線程返回future結果: the thread is 2
已完成
已完成線程返回future結果: the thread is 3
未完成
4-pool-1-thread-2 is working...
已完成線程返回future結果: the thread is 4
-------------
更多的Java,Angular,Android,大數據,J2EE,Python,數據庫,Linux,Java架構師,:
http://www.cnblogs.com/zengmiaogen/p/7083694.html