线程类:
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