记录-自用
JDK提供了很多开发工具,经过多个版本的迭代完善,同样功能的api可能也会经过多次维护,更新。所以平时使用选用合适的api很重要,个人记录demo:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class EntryTestClass {
/**线程池参数*/
private static final long KEEP_ALIVE_TIME = 500L;
private static final int CORE_POOL_SIZE = 5;
private static final int MAX_POOL_SIZE = 5;
/**
* 线程池初始化
*/
private static ThreadPoolExecutor initThreadPool() {
return new ThreadPoolExecutor(
// core pool size
CORE_POOL_SIZE,
// max pool size
MAX_POOL_SIZE,
// keep alive time
KEEP_ALIVE_TIME, TimeUnit.MILLISECONDS,
// queue
new LinkedBlockingQueue<>(),
// handler
new ThreadPoolExecutor.CallerRunsPolicy());
}
public static void main(String[] args) {
List<TestCallableTask> taskList = new ArrayList<>();
for(int i=0;i<=100;i++){
TestCallableTask task = new TestCallableTask(i);
taskList.add(task);
}
ThreadPoolExecutor executor = initThreadPool();
try {
//阻塞式api
//executor.invokeAll(taskList);
executor.invokeAll(taskList,100,TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("execute End");
executor.shutdown();
}
}
/**
* 线程池子任务
*/
class TestCallableTask implements Callable<String> {
/**标识,创建任务的顺序*/
private int num;
@Override
public String call() throws Exception {
System.out.println("call execute"+num);
return "";
}
public TestCallableTask(int num){
this.num=num;
}
}
寻根问底来看一下内部是怎么实现的,逻辑很简单:
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException {
if (tasks == null)
throw new NullPointerException();
long nanos = unit.toNanos(timeout);
//内部执行列表
ArrayList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
boolean done = false;
try {
//遍历组织数据,不写括号差评!
for (Callable<T> t : tasks)
futures.add(newTaskFor(t));
final long deadline = System.nanoTime() + nanos;
final int size = futures.size();
// Interleave time checks and calls to execute in case
// executor doesn't have any/much parallelism.
for (int i = 0; i < size; i++) {
execute((Runnable)futures.get(i));
nanos = deadline - System.nanoTime();
if (nanos <= 0L)
return futures;
}
//获取线程执行结果,未结束情况下,若超时则即使任务未完成也返回掉,未超时则继续等待
for (int i = 0; i < size; i++) {
Future<T> f = futures.get(i);
if (!f.isDone()) {
if (nanos <= 0L)
return futures;
try {
f.get(nanos, TimeUnit.NANOSECONDS);
} catch (CancellationException ignore) {
} catch (ExecutionException ignore) {
} catch (TimeoutException toe) {
return futures;
}
nanos = deadline - System.nanoTime();
}
}
done = true;
return futures;
} finally {
if (!done)
for (int i = 0, size = futures.size(); i < size; i++)
futures.get(i).cancel(true);
}
}