/** MyCallableA 实现Callable接口 **/
package com.product.supermiketho.threaddemo;
import java.util.concurrent.Callable;
public class MyCallableA implements Callable<MyVo> {
@Override
public MyVo call() throws Exception {
Thread.sleep(5000);
return new MyVo("A001","A结果");
}
}
/** MyCallableB 实现Callable接口 **/
package com.product.supermiketho.threaddemo;
import java.util.concurrent.Callable;
public class MyCallableB implements Callable<MyVo> {
@Override
public MyVo call() throws Exception {
Thread.sleep(5000);
return new MyVo("B001","B结果");
}
}
/** MyCallableC 实现Callable接口 **/
package com.product.supermiketho.threaddemo;
import java.util.concurrent.Callable;
public class MyCallableC implements Callable<MyVo> {
@Override
public MyVo call() throws Exception {
Thread.sleep(5000);
return new MyVo("C001","c结果");
}
}
/**测试类 **/
package com.product.supermiketho.threaddemo;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 执行入口
*/
public class CallableRun {
public static void main(String[] args) {
long start = System.currentTimeMillis();
List<Future<Integer>> futureTasks = new ArrayList<>();
/**
* 参数:
* corePoolSize–池中要保留的线程数,即使它们处于空闲状态,除非设置了allowCoreThreadTimeOut
* maximumPoolSize–池中允许的最大线程数
* keepAliveTime–当线程数大于核心时,这是多余的空闲线程在终止前等待新任务的最长时间。
* unit–keepAliveTime参数的时间单位
* workQueue–用于在执行任务之前保存任务的队列。此队列将仅保存execute方法提交的Runnable任务。
* IllegalArgumentException–如果以下情况之一成立:corePoolSize<0 keepAliveTime<0 maximumPoolSize<=0 maximumPoolSize<corePoolSize
* NullPointerException–如果工作队列为空
*/
ThreadPoolExecutor pool = new ThreadPoolExecutor(3, 3, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
try {
MyCallableA theCallable = new MyCallableA( );
Future f = pool.submit(theCallable);
futureTasks.add(f);
MyCallableB theCallableB = new MyCallableB( );
Future fB = pool.submit(theCallableB);
futureTasks.add(fB);
MyCallableC theCallableC = new MyCallableC( );
Future fC = pool.submit(theCallableC);
futureTasks.add(fC);
System.out.println("线程 " + futureTasks.size());
for (Future v : futureTasks) {
MyVo obj = (MyVo) v.get();
System.out.println( "getCode---"+obj.getCode() + " getMsg---"+obj.getMsg());
}
pool.shutdown();
long end = System.currentTimeMillis();
System.out.println("耗时:{} ms" + (end - start));
} catch (Exception e) {
e.printStackTrace();
}
}
}
测试结果 :
线程 3
getCode---A001 getMsg---A结果
getCode---B001 getMsg---B结果
getCode---C001 getMsg---c结果
耗时:{} ms5041
结论:
MyCallableA ,MyCallableB ,MyCallableC 分别sleep了5s,
最后执行总耗时约为5秒,说明各线程已经异步执行(由线程池分配线程),并阻塞收集结果返回。