线程池用法

每次都写每次都查记录成册,以后就看这里。

  1. 创建线程池
  2. 线程池+runable
  3. 线程池+callable+异步获取
  4. 线程池+callable+同步获取

线程池+runable
创建线程池

package com.example.demo.threadPool;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class MyThreadPool {
    public static ThreadPoolExecutor newInstance() {
        return SingletonHolder.threadPoolExecutor;
    }
    /**
     * 定义cpu核数+3数量的线程池
     * 静态内部类方式使用时创建,线程安全
     */
    public static class SingletonHolder{
        private static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors()/2;
        private static final int MAX_POOL_SIZE = Runtime.getRuntime().availableProcessors();
        private static final int QUEUE_CAPACITY = 1000;
        private static final Long KEEP_ALIVE_TIME = 1L;
        private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                CORE_POOL_SIZE,
                MAX_POOL_SIZE,
                KEEP_ALIVE_TIME,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(QUEUE_CAPACITY),
                new ThreadPoolExecutor.CallerRunsPolicy());
    }
}

runable实现

package com.example.demo.threadPool;

public class TestRunable implements Runnable {
    @Override
    public void run() {
        System.out.println("子线程开始");
            // 子线程休眠五秒
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("子线程结束");
    }
}

controller调用`

    @PostMapping("upload3")
    public void upload3() throws Exception {
        ThreadPoolExecutor pools = MyThreadPool.newInstance();
        TestRunable testRunable = new TestRunable();
        pools.submit(testRunable);
        pools.submit(testRunable);
        pools.submit(testRunable);
        pools.submit(testRunable);
    }

至此线程池+runable就完成了

线程池+callable实现+异步获取
callable实现

package com.example.demo.threadPool;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

public class OneTask implements Callable {
    private int time;
    private String name;
    public OneTask(int time,String name) {
        this.time = time ;
        this.name = name;
    }
    @Override
    public String call() throws Exception {
        TimeUnit.SECONDS.sleep(this.time) ;
        return name+"---success";
    }
}

controller’调用

    @PostMapping("upload1")
    public String upload1() throws Exception {
        ThreadPoolExecutor pool =
                new ThreadPoolExecutor(3, 3, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10)) ;
        CompletionService<String> cs = new ExecutorCompletionService<>(pool) ;
        cs.submit(new OneTask(3, "name" + 3)) ;
        cs.submit(new OneTask(1, "name" + 1)) ;
        cs.submit(new OneTask(2, "name" + 2)) ;
        for (int i = 0; i < 3; i++) {
            String s = cs.take().get();
            log.info("获取返回结果---"+s);
        }
        pool.shutdown();
        return "success";
    }

可以看到打印出的顺序事1、2、3刚好符合预期目标,3耗时最长第一个调用但最后返回,1最后调用耗时最短最先返回,CompletionService对象的cs.take().get()异步获取结果,三个任务按照各自执行的速度谁先完成先拿到谁的结果

[nio-8080-exec-2] c.e.d.controller.EasyExcelBIoController  : 获取返回结果---name1---success
[nio-8080-exec-2] c.e.d.controller.EasyExcelBIoController  : 获取返回结果---name2---success
[nio-8080-exec-2] c.e.d.controller.EasyExcelBIoController  : 获取返回结果---name3---success

至此线程池+callable实现+异步获取完成

线程池+callable+同步获取
callable实现同上
controller调用

    @PostMapping("upload2")
    public String upload2() throws Exception {
        ThreadPoolExecutor pool = 
                new ThreadPoolExecutor(3, 3, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10)) ;
        Future f1 = pool.submit(new OneTask(3, "name" + 3));
        Future f2 = pool.submit(new OneTask(1, "name" + 1));
        Future f3 = pool.submit(new OneTask(2, "name" + 2));
        List<Future> futures = Arrays.asList(f1, f2, f3);
        for (Future future : futures) {
            Object o = future.get();
            log.info("获取返回结果---"+o);
        }
        pool.shutdown();
        return "success";
    }

可以看到打印出的顺序事3、1、2刚好符合预期目标3耗时最长只有等3返回了1和2才返回,future.get()同步获取结果。

[nio-8080-exec-5] c.e.d.controller.EasyExcelBIoController  : 获取返回结果---name3---success
[nio-8080-exec-5] c.e.d.controller.EasyExcelBIoController  : 获取返回结果---name1---success
[nio-8080-exec-5] c.e.d.controller.EasyExcelBIoController  : 获取返回结果---name2---success

至此线程池+callable+同步获取完成

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值