Exectutors
//以下为各种起线程池方式
//ExecutorService threadPool = Executors.newFixedThreadPool(3);
//ExecutorService threadPool = Executors.newCachedThreadPool();
// ExecutorService threadPool = Executors.newSingleThreadExecutor();
//等待6秒后间隔2秒就定时任务调起,
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(
new Runnable(){
@Override
public void run() {
System.out.println("bombing!");
}},
6,
2,
TimeUnit.SECONDS);
/./起一个单例线程,线程死了会重新拉起来
ExecutorService threadPool = Executors.newSingleThreadExecutor();
//通过Future对象可获取线程返回结果
Future<String> future =
threadPool.submit(
new Callable<String>() {
public String call() throws Exception {
Thread.sleep(2000);
return "hello";
};
}
);
//等待线程返回结果打印出来
System.out.println(“thread return: ”+ future.get());
-------------------------------------------------------------
//创建一个10个纯种的线程池
ExecutorService threadPool2 = Executors.newFixedThreadPool(10);
//CompletionService可以获取先运行结束的线程返回
CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2);
//提交10个任务
for(int i=1;i<=10;i++){
final int seq = i;
completionService.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep(new Random().nextInt(5000));
return seq;
}
});
}
//等待10个任务的线程返回结果(先运行完的为第一个返回)
for(int i=0;i<10;i++){
try {
System.out.println(
completionService.take().get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}