FutureTask的使用
生活随笔
收集整理的這篇文章主要介紹了
FutureTask的使用
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一、例子:
package com.cy.test.concurrent;import com.google.common.collect.Lists; import java.util.List; import java.util.concurrent.*;/*** 測試future Task*/ public class FutureTest {private static ExecutorService pool = Executors.newFixedThreadPool(5);public static void main(String[] args) {List<FutureTask<String>> taskList = Lists.newArrayList();for(int i=0; i<5; i++){final int temp = i;FutureTask<String> future = new FutureTask<String>(new Callable<String>() {@Overridepublic String call() throws Exception {Thread.sleep(3000);return "zhangsan" + temp;}});//pool.execute(future);new Thread(future).start();taskList.add(future);}List<String> nameList = Lists.newArrayList();for(FutureTask<String> future : taskList){try {nameList.add(future.get());} catch (Exception e) {e.printStackTrace();}}System.out.println(nameList);} }console輸出:
[zhangsan0, zhangsan1, zhangsan2, zhangsan3, zhangsan4]?
二、可以參考這篇博客對future、callable的說明:http://www.cnblogs.com/dolphin0520/p/3949310.html
轉(zhuǎn)載于:https://www.cnblogs.com/tenWood/p/10020966.html
總結(jié)
以上是生活随笔為你收集整理的FutureTask的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: char* 和 char * 思考
- 下一篇: 编程3:仅用递归函数和栈操作逆序一个栈