日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

线程池与Callable更配哦

發(fā)布時間:2025/3/11 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 线程池与Callable更配哦 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

概述

Callable介紹見:http://blog.csdn.net/zengmingen/article/details/53288119

多線程介紹見:http://blog.csdn.net/zengmingen/article/details/53284999


代碼

TaskCallable.java

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,大數(shù)據(jù),J2EE,Python,數(shù)據(jù)庫,Linux,Java架構師,:

http://www.cnblogs.com/zengmiaogen/p/7083694.html


總結

以上是生活随笔為你收集整理的线程池与Callable更配哦的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。