Java5之后提供了线程池ThreadPool,
concurrent包下的Executors提供了很多创建线程池的方法,根据不同需要,分开使用。包括但不限于 newFixedThreadPool固定大小的线程池,newCachedThreadPool缓存线程池(根据线程多少创建线程数),newSingleThreadExecutor单线程(保证有一个线程),newScheduledThreadPool(定时器线程池).....
上代码
public class ThreadPoolTest {
public static void main(String[] args) {
//ExecutorService threadPool = Executors.newFixedThreadPool(3);
//ExecutorService threadPool = Executors.newCachedThreadPool();
ExecutorService threadPool = Executors.newSingleThreadExecutor();
for(int i=1;i<=10;i++){
final int task = i;
threadPool.execute(new Runnable(){
@Override
public void run() {
for(int j=1;j<=10;j++){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " is looping of " + j + " for task of " + task);
}
}
});
}
System.out.println("all of 10 tasks have committed! ");
//threadPool.shutdownNow();
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(
new Runnable(){
@Override
public void run() {
System.out.println("bombing!");
}},
6,
2,
TimeUnit.SECONDS);
}
}
实际代码要注意使用try catch finally,根据需要在finally里关闭线程池。上述代码在jdk1.8之后使用lambda表达式后为
public class ThreadPoolTest {
public static void main(String[] args) {
//ExecutorService threadPool = Executors.newFixedThreadPool(3);
//ExecutorService threadPool = Executors.newCachedThreadPool();
ExecutorService threadPool = Executors.newSingleThreadExecutor();
for(int i=1;i<=10;i++){
final int task = i;
threadPool.execute(() -> {
for(int j=1;j<=10;j++){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " is looping of " + j + " for task of " + task);
}
});
}
System.out.println("all of 10 tasks have committed! ");
//threadPool.shutdownNow();
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(
() -> System.out.println("bombing!"),
6,
2,
TimeUnit.SECONDS);
}
}
当有返回结果时,使用callable和future代替runnable
上代码学姿势
ExecutorService threadPool = Executors.newSingleThreadExecutor();
Future<String> future =
threadPool.submit(
() -> {
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 (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
当有一组Callable任务需要提交时,使用CompletionService,期take()方法返回对应的Future对象
上代码
ExecutorService threadPool2 = Executors.newFixedThreadPool(10);
CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2);
for(int i=1;i<=10;i++){
final int seq = i;
completionService.submit(() -> {
Thread.sleep(new Random().nextInt(5000));
return seq;
});
}
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();
}
}