Java新手也能轻松hold住的多线程编程方式

少量耗时任务

生产环境不建议使用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());
		
		// 执行一些需要等待所有耗时任务都完成的其他任务
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值