多线程优化代码

首先可以用线程池定义多个线程。

// 静态化避免重复创建,初始化10个线程
	private static final ExecutorService executor = Executors.newFixedThreadPool(10);
public void test() {
//这里是封装的类,该类实现Runnable接口
		Test task = new Test();
		//通过线程池对象执行该方法
		executor.execute(task);
	}
class Test implements Runnable{
//定义好参数
  private String A;
  private String B;
//再定义一个构造器
		public Test(String A,String B){
			this.A=A;
			this.B=B;
		}
		@Override
		public void run() {
		//这里就是写线程执行的方法了。异步代码大致就形成了,这样可以提高效率当接口返回时间较慢时候。
}

另外多线程我发现可以用来优化for循环语句,如果当for循环里面嵌套了多层循环,可以尝试用stream流以及多线程来优化,提高执行效率,反正多线程跟和stream流yyds。

if (CollectionUtils.isNotEmpty(list)) {
            int listSize = list.size();
            //  子线程计数器
            CountDownLatch childThreadCountDownLatch = new CountDownLatch(listSize);
            for (User record : list) {
                executor.execute(() -> {
                    try {
                        User user= userService.getDetails(record.getUser(), record.getName(), startDay, endDay);
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error("查询发生异常,异常内容:{}", e.getMessage());
                    } finally {
                        //线程任务完成后
                        childThreadCountDownLatch.countDown();
                    }
                });
            }
            try {
                childThreadCountDownLatch.await();// 主线程在阻塞,等待线程执行完成
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
           
//定义线程池最大容量5个线程
 private static final ExecutorService executor = Executors.newFixedThreadPool(5);


    /**
     * @param args
     */
    public static void main(String[] args) {
        final int[] tickets = {70};
        CountDownLatch countDownLatch = new CountDownLatch(tickets.length);
        //模拟60个客户买票,由五个线程去完成
        for (int i = 60; i > 0; i--) {
            executor.execute(() -> {
                while (true) {
                    try {
                        if (tickets[0] > 0) {
                            System.out.println(Thread.currentThread().getName() + "出售票" + tickets[0]--);
                        }
                    } catch (Exception e) {
                        log.info("出错了");
                    } finally {
                        countDownLatch.countDown();
                    }
                }
            });
        }
        try {
            countDownLatch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不会敲代码阿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值