package com.knowledge.thread;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* 有返回值的线程 测试
* @author yangql
* @date Feb 2, 2018 9:40:33 AM
*/
public class Test {
/**ExecutoreService提供了submit()方法,传递一个Callable,或Runnable,
* 返回Future。如果Executor后台线程池还没有完成Callable的计算,
* 这调用返回Future对象的get()方法,会阻塞直到计算完成
* @param args
* @throws InterruptedException
* @throws ExecutionException
* @author yangql
* @date Feb 2, 2018 9:49:06 AM
*/
public static void main(String[] args) throws InterruptedException, ExecutionException {
int taskSize = 5;
// 创建一个线程池
ExecutorService pool = Executors.newFixedThreadPool(taskSize);
// 创建多个有返回值的任务
List<Future> list = new ArrayList<Future>();
for (int i = 0; i < taskSize; i++) {
Callable c = new CallableTest(i + "");
// 执行任务并获取Future对象
Future f = pool.submit(c);
// System.out.println(">>>" + f.get().toString());
list.add(f);
}
// 关闭线程池
pool.shutdown();
// 获取所有并发任务的运行结果
for (Future f : list) {
// 从Future对象上获取任务的返回值,并输出到控制台
System.out.println(">>>" + f.get().toString());
}
}
}
import java.util.concurrent.Callable;
public class CallableTest implements Callable<Object>{
private String taskSequence;
CallableTest(String taskSequence){
this.taskSequence = taskSequence;
}
@Override
public Object call() throws Exception {
return taskSequence+"---任务正在执行";
}
}