jdk原生线程池同步&异步使用方法举例

线程池使用例子

package com.chen.hi.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class ThreadPoolExecutorTest {
    class Task implements Callable<String> {
        private String taskProperty;

        public Task(String taskProperty) {
            this.taskProperty = taskProperty;
        }

        @Override
        public String call() throws InterruptedException {
            Thread.sleep(1000);
            System.out.println("完成:" + taskProperty);
            return "返回值:" + taskProperty;
        }
    }

    public void start() throws ExecutionException, InterruptedException {
        //创建线程池,并发量最大为5,因为是linked,所以队列不会满
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                5, 10,
                1, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(),
                new ThreadPoolExecutor.CallerRunsPolicy());
        //用于存储线程的返回值
        List<Future<String>> results = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            Task task = new Task(String.valueOf(i));
            System.out.println("放入线程池:" + i);
            //调用submit可以获得线程的返回值
            Future<String> result = threadPoolExecutor.submit(task);
            //execute直接进行异步,不获得返回值
            int finalI = i;
            threadPoolExecutor.execute(() -> threadPoolDo(String.valueOf(finalI)));
            results.add(result);
        }
        //此函数表示不再接收新任务,
        //如果不调用,awaitTermination将一直阻塞
        threadPoolExecutor.shutdown();
        //1天,模拟永远等待
        System.out.println(threadPoolExecutor.awaitTermination(1, TimeUnit.DAYS));
        //输出结果
        for (int i = 0; i < 10; i++) {
            System.out.println(results.get(i).get());
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadPoolExecutorTest test = new ThreadPoolExecutorTest();
        test.start();
    }

    private void threadPoolDo(String name) {
        System.out.println("执行直接异步任务:" + name);
    }
}

spring boot下如何使用

这边我使用伪代码展示,因为spring cloud相关配置什么得比较麻烦

@Component
public class TestService {
    //线程池
    private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1000));
    //某个需要应用的其他spring cloud服务
    @Resource
    private OtherService otherService;

    public String getResult(TestReuquest rq) throws ExecutionException, InterruptedException {
        List<Future<String>> resultDOList = new ArrayList<>();
        //调用其他微服务
        for (int i = 0; i < 10; i++) {
            //不需要结果值得异步
            int finalI = i;
            threadPoolExecutor.execute(() -> threadPoolDo(String.valueOf(finalI)));
            //需要结果值得异步
            Task task = new Task(String.valueOf(i));
            Future<String> future = threadPoolExecutor.submit(task);
            resultDOList.add(future);
        }
        for (Future<String> future : resultDOList) {
            //获得微服务的结果值
            String result = future.get();
        }
        return "true";
    }

    private void threadPoolDo(String name) {
        otherService.doSomeThing(name);
    }

    //注意Callable中的string就是返回的结果值
    class Task implements Callable<String> {
        private String taskProperty;

        public Task(String taskProperty) {
            this.taskProperty = taskProperty;
        }

        @Override
        public String call() throws Exception {
            String result = otherService.doSomeThing(taskProperty);
            return result;
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值