import java.util.concurrent.Callable;
public class MyCallable implements Callable<String> {
private String name;
public MyCallable(String name){
this.name=name;
}
@Override
public String call() throws Exception {
System.out.println("Thread begin "+name);
Thread.sleep(1000);
return name;
}
}
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class DynamicThreadPool {
public static void main(String[] args) {
/*ThreadPoolExecutor taskExecutor = new ThreadPoolExecutor(
1,100,5, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(100), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());*/
ThreadPoolExecutor taskExecutor = new ThreadPoolExecutor(
1,100,5, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
long a=System.nanoTime();
CompletionService<String> cs = new ExecutorCompletionService<>(taskExecutor);
for (int i = 0; i < 100; i++) {
cs.submit(new MyCallable("Thread "+i));
}
for (int i = 0; i < 100; i++){
try {
System.out.println(cs.take().get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(System.nanoTime()-a);
}
任务数(1任务耗时1秒) 用时(纳秒) 队列长度
SynchronousQueue 100 1010688455
LinkedBlockingQueue 100 太长 100
SynchronousQueue 1000 12041095086
LinkedBlockingQueue 1000 10073587003 100
SynchronousQueue 10000 129230529016
LinkedBlockingQueue 10000 100583218224 100