少量耗时任务
生产环境不建议使用new Thread(()->{}).start()显式创建线程或者Executors创建线程池,最好通过ThreadPoolExecutor创建线程池,明确指定各个参数,假设只有两个任务:
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TestMultiThread {
public static void main(String[] args) throws InterruptedException {
// 多少个任务
int n = 2;
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(n, n, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
CountDownLatch countDownLatch = new CountDownLatch(n);
threadPoolExecutor.execute(() -> {
// 处理任务1
// 当执行完毕
countDownLatch.countDown();
});
threadPoolExecutor.execute(() -> {
// 处理任务2
// 当执行完毕
countDownLatch.countDown();
});
// 等待
countDownLatch.await();
threadPoolExecutor.shutdown();
// 执行其他需要等待任务1和任务2都执行完毕的任务
}
}
大量重复耗时任务
使用Java8 parallel stream,底层使用fork join线程模型:
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class TestMultiThread {
public static void main(String[] args) {
List<String> resultList = IntStream.range(0, 100).parallel().mapToObj(i -> {
// 重复的耗时任务并返回结果,比如http请求
return "result";
}).collect(Collectors.toList());
// 执行一些需要等待所有耗时任务都完成的其他任务
}
}