本代码阐述:
- 使用Executors创建线程池
- 使用Callable定义执行主体(带返回值)
- 使用Future进行返回内容接收
package com.mine.concurrent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
/**
* 并发编程实战1:
* Executors + Callable + Thread.sleep
*/
public class Demo1 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(3);
List<Future<Integer>> list = new ArrayList<Future<Integer>>();
for (int i = 0; i < 10; i++) {
list.add(executorService.submit(new MyCallable(i)));
}
for (Future<Integer> future : list) {
// 拿到任务结果(这里是依次拿的)
System.out.println(future.get());
}
}
public static class MyCallable implements Callable<Integer> {
private final int number;
public MyCallable(int number) {
this.number = number;
}
public Integer call() throws Exception {
System.out.println(String.format("任务%d开始", number));
Random random = new Random();
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException e) {
// 抛出运行时异常,而不是吞噬异常
throw new RuntimeException(e);
}
System.out.println(String.format("任务%d结束", number));
return number;
}
}
}
- Executors创建固定的线程池
- ExecutorService的submit方法可以返回Future,用来监控运行结果和做更多的控制
- Callable可以有返回值,这是与Runnable的不同点
- Thread.sleep + random.nextInt 可以随机睡眠时间