Creating Four thread pool

It can greatly reduce the thread pool thread creation, destruction caused by the waste of resources. It can manage and reuse of thread.

1 newCachedThreadPool

/**
 * 创建可以缓存的线程池,如果线程长度大于预期,
 * 线程池会灵活的创建新线程和回收空闲的线程。
 */
 
public class newCachedThreadPool {
    public static void main(String[] args) {
        ExecutorService cacheThreadPool = Executors.newCachedThreadPool();
        for (int i=0 ; i < 5 ; i++){
            final int temp = i ;
            try{
                Thread.sleep(10);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            cacheThreadPool.execute(() ->{
                System.out.println(temp);
            });
        }
    }
}

operation result:
Here Insert Picture Description

2 newFixedThreadPool

/**
 * 创建一个固定长度的线程池,如果线程大于线程池的长度,
 * 则超出范围的线程需要进入队列等待
 */
 
public class newFixedThreadPool {
    public static void main(String[] args) {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3) ;
        for (int i=0 ; i<5 ; i++){
            final int temp = i ;
            fixedThreadPool.execute(()->{
                try {
                    System.out.println(temp);
                    Thread.sleep(10);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            });
        }
    }
}

operation result:
Here Insert Picture Description

3 newScheduledThreadPool

/**
 * 创建一个固定长度的线程池,此线程池支持定时任务和周期任务。 
 */
public class newScheduledThreadPool {
    public static void main(String[] args) {
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3) ;
        for (int i=0 ; i<5 ; i++){
            scheduledThreadPool.schedule(new Runnable() {
                @Override
                public void run() {
                    System.out.println("数五个数");
                }
            } , 5 , TimeUnit.SECONDS) ;
        }
    }
}

operation result:

This is the result of running out of five seconds
Here Insert Picture Description

4 newSingleThreadExecutorPool

/**
 * 单线程的线程池,只用一个线程来执行程序,其他线程保存到LinkedBlockingQueue中,  
 * 保证任务按照顺序执行,优先级或者FIFO
 */
public class newSingleThreadExecutorPool {
    public static void main(String[] args) {
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor() ;

        for (int i=0 ; i<5 ; i++){
            final int temp = i ;
            singleThreadExecutor.execute(()->{
                try{
                    System.out.println(temp);
                    Thread.sleep(2000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            });
        }
    }
}

The result:
Each print out the results of time separated by two seconds
Here Insert Picture Description

Published 56 original articles · won praise 3 · Views 1199

Guess you like

Origin blog.csdn.net/qq_40788718/article/details/103104205
Recommended