欢迎来到DIVCSS5查找CSS资料与学习DIV CSS布局技术!
线程池无非就那几个参数:核心线程、最大线程、回收时间、队列,没啥难的,有手就能学废
 
我这里直接上demo,不知道参数啥意思的可以先去隔壁补补课,虽然本文也会提到,但你最好先大概知道点,线程池实现运行机制总结
 
上才艺
 
public class ThreadPoolExecutorTest {
 
    private static int taskCount = 50;//任务数
 
    private static AtomicInteger taskCountExecuted;//实际完成任务数
 
    public static void main(String[] args) {
 
        taskCountExecuted = new AtomicInteger();
 
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
 
                10,//核心线程数
 
                20,//最大线程数
 
                5,//非核心回收超时时间
 
                TimeUnit.SECONDS,//超时时间单位
 
                new ArrayBlockingQueue<>(30)//任务队列
 
        );
 
        System.out.println("总任务数:" + taskCount);
 
        long start = System.currentTimeMillis();
 
        //模拟任务提交
 
        for (int i = 0; i < taskCount; i++) {
 
            Thread thread = new Thread(() -> {
 
                try {
 
                    Thread.sleep(500);//模拟执行耗时
 
                    System.out.println("已执行" + taskCountExecuted.addAndGet(1) + "个任务");
 
                } catch (InterruptedException e) {
 
                    e.printStackTrace();
 
                }
 
            });
 
            try {
 
                //注意这里我try起来了,默认拒绝策略会报错
 
                executor.execute(thread);
 
            } catch (RejectedExecutionException e) {
 
                taskCount = executor.getActiveCount() + executor.getQueue()。size();
 
            }
 
        }
 
        long end = 0;
 
        while (executor.getCompletedTaskCount() < taskCount) {
 
            end = System.currentTimeMillis();
 
        }
 
        System.out.println(taskCountExecuted + "个任务已执行,总耗时:" + (end - start));
 
        executor.shutdown();
 
    }
 
}

如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h64793.shtml