victory的博客

长安一片月,万户捣衣声

0%

Java | 创建线程池的7种方式

创建线程池的7种方式

import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolCreationTest {
    public static void fixedThreadPool(){
//        ExecutorService threadPool = Executors.newFixedThreadPool(2);
//        
//        Runnable runnable = new Runnable(){
//            @Override
//            public void run(){
//                System.out.println("任务被执行,线程:" + Thread.currentThread().getName());
//            }
//        };
//        
//        Future<?> submit = threadPool.submit(runnable);
////        System.out.println(submit);
////        System.out.println(submit.isDone());
//        threadPool.execute(runnable);
//        threadPool.execute(runnable);
//        threadPool.execute(runnable);
        
        ExecutorService threadPool = Executors.newFixedThreadPool(2);
        for(int i = 0; i < 4; i++){
            threadPool.execute(() -> {
                System.out.println("任务被执行,线程:" + Thread.currentThread().getName());
            });
        }
    }
    
    public static void cachedThreadPool(){
        ExecutorService threadPool = Executors.newCachedThreadPool();
        for(int i=0;i<10;i++){
            threadPool.execute(() -> {
                System.out.println("任务被执行,线程:" + Thread.currentThread().getName());
            });
        }
    }
    
    public static void singleThreadPool(){
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        for(int i = 0; i < 10; i++){
            threadPool.execute(() -> {
                System.out.println("任务被执行,线程:" + Thread.currentThread().getName());
            });
        }
    }
    
    public static void scheduledThreadPool(){
        ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(5);
        System.out.println("添加任务,时间:"+new Date());
        threadPool.schedule(()->{
            System.out.println("任务被执行,时间:"+new Date());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, 1, TimeUnit.SECONDS);
    }
    
    public static void singleThreadScheduledPool(){
        ScheduledExecutorService threadPool = Executors.newSingleThreadScheduledExecutor();
        System.out.println("添加任务,时间:"+new Date());
        threadPool.schedule(()->{
            System.out.println("任务被执行,时间:"+new Date());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, 2, TimeUnit.SECONDS);
    }
    
    public static void workStealingPool(){
        ExecutorService threadPool = Executors.newWorkStealingPool();
        for(int i = 0; i < 10; i++){
            final int index = i;
            threadPool.execute(() ->{
                System.out.println(index + "被执行,线程名"+Thread.currentThread().getName());
            });
        }
        while(!threadPool.isTerminated()){
            
        }
    }
    
    //推荐使用
    //阿里巴巴开发手册:线程池不允许使用 Executors 去创建,而是通过 ThreadPoolExecutor 的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。
    public static void myThreadPoolExecutor(){
        final int CORE_POOL_SIZE = 5;  
        final int MAX_POOL_SIZE = 10;
        final int QUEUE_CAPACITY = 100;
        final Long KEEP_ALIVE_TIME = 1L;
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                CORE_POOL_SIZE,
                MAX_POOL_SIZE,
                KEEP_ALIVE_TIME,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(QUEUE_CAPACITY),
                new ThreadPoolExecutor.CallerRunsPolicy()
                );
        for(int i = 0; i < 10; i++){
            final int index = i;
            threadPool.execute(() -> {
                System.out.println(index+"被执行,线程名:"+Thread.currentThread().getName());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        
    }
    
    
    public static void main(String[] args) {
        //fixedThreadPool();
        //cachedThreadPool();
        //singleThreadPool();
        //scheduledThreadPool();
        //singleThreadScheduledPool();
        //workStealingPool();
        myThreadPoolExecutor();
    }
}