自定义线程池以及参数的合理分配

/**
 * 第4种获得/使用java多线程的方式,线程池
 */
public class MyThreadPoolDemo {

    public static void main(String[] args) {

        //查看cpu核心数 从而 合理的配置线程池的容量
        System.out.println(Runtime.getRuntime().availableProcessors());

        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                2,
                5,
                1L,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),  //候课区大小
                Executors.defaultThreadFactory(),
                // new ThreadPoolExecutor.AbortPolicy()   //使用默认拒绝策略  超出max和阻塞区的大小直接抛出异常
                //new ThreadPoolExecutor.CallerRunsPolicy()  //超过了回退给调用者线程
                //new ThreadPoolExecutor.DiscardOldestPolicy()
                new ThreadPoolExecutor.DiscardPolicy()
        );

        try {
            for (int i = 1; i <=10; i++) {
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"\t 业务办理");
                });

            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }
    }
    }

你可能感兴趣的:(多线程)