Java中的线程池

package com.cn.gbx;

import java.util.Date;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future; public class TestThread { public static void main(String[] args) { //Java中提供的三个线程池
// ExecutorService threadPool = Executors.newCachedThreadPool();
// ExecutorService threadPool2 = Executors.newFixedThreadPool(3);
// ExecutorService threadPool3 = Executors.newSingleThreadExecutor();
// for (int i = 1; i <= 10; ++i) {
// final int task = i;
// threadPool.execute( new Runnable() {
// public void run() {
// for (int j = 1; j <= 10; ++j) {
// System.out.println(Thread.currentThread().getName() + " is looping " + j + " at task " + task);
// }
// }
// });
// }
// threadPool.shutdown(); // Callable 与 future 的应用 // ExecutorService threadPool = Executors.newCachedThreadPool();
// Future<String> future = threadPool.submit(
// new Callable<String>() {
// @Override
// public String call() throws Exception {
// Thread.sleep(2000);
// return "hello";
// }
// }
// );
// System.out.println("等待结果:");
// try {
// System.out.println("结果为: " + future.get());
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (ExecutionException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } //利用CompletionService提交一组 Callable
ExecutorService threadPool = Executors.newCachedThreadPool();
CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool);
for (int i = 1; i <= 10; ++i) {
final int seq = i;
completionService.submit(
new Callable<Integer>() { @Override
public Integer call() throws Exception {
Thread.sleep(2000);
return seq;
}
}
);
}
for (int i = 1; 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();
}
}
}
}

  

上一篇:JSON详解以及可以把javabean转换成json串的json-lib应用


下一篇:Atitit php java python nodejs错误日志功能的比较