多線程返回值問題?
import java.util.concurrent.Callable;
/**
* 線程類,需要返回值的 ,實現Callable接口
* @author xhc
*
*/
@SuppressWarnings("rawtypes")
public class MyThread implements Callable{
@SuppressWarnings("static-access")
@Override
public Object call() throws Exception {
Thread.currentThread().sleep(1000);//睡眠一秒
return Thread.currentThread().getName();
}
}
測試類:
package com.xjiuge.test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class App {
//建立線程池
static ExecutorService pool = Executors.newCachedThreadPool();
@SuppressWarnings("unchecked")
public static void main(String[] args) {
//存放future的集合
List<Future<String>> list = new ArrayList<>();
long st = System.currentTimeMillis();//開始時間
//循環5次,開啟5個線程
for (int i = 0; i < 5; i++) {
//獲取線程類返回的值,用future接收
Future<String> future = pool.submit(new MyThread());
//將future放入list
list.add(future);
}
try {
//遍歷list讀取future中的值
for (Future<String> future : list) {
while(true) {
//判斷線程操作是否執行完畢,并且操作沒有被取消掉
if(future.isDone() && !future.isCancelled()) {
//調用get方法獲取返回值
String result = future.get().toString();
System.out.println(result);
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
long et = System.currentTimeMillis();//結束時間
System.out.println("總耗時:" + (et - st) + "ms");
}
}
打印結果:
pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
pool-1-thread-4
pool-1-thread-5
總耗時:1004ms