1. 程式人生 > 實用技巧 >linux簡單軟體安裝

linux簡單軟體安裝

1. 為什麼使用執行緒池

1、降低資源的消耗
2、提高響應的速度
3、方便管理。
執行緒池可以達到:執行緒複用、可以控制最大併發數、管理執行緒的目的

2. 執行緒池的使用

2.1 Executors的三種方法

package pool;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * study01
 *
 * @author : xgj
 * @description : de
 * @date : 2020-09-21 10:18
 **/
public class ThreadPool {
    public static void main(String[] args) {
        //建立只有一個執行緒的執行緒池,但是其阻塞佇列長度可以達到Integer.MAX_VALUE
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        for (int i = 0; i <10 ; i++) {
            threadPool.execute(()->{
                  //輸出執行緒名
                System.out.println(Thread.currentThread().getName());
            });
        }
        //使用完成後需要進行關閉
        threadPool.shutdown();
        
    }
}

執行截圖

package pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * study01
 *
 * @author : xgj
 * @description : de
 * @date : 2020-09-21 10:18
 **/
public class ThreadPool {
    public static void main(String[] args) {
        //建立指定個數的執行緒池,其阻塞佇列長度可以達到Integer.MAX_VALUE
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        for (int i = 0; i <10 ; i++) {
            threadPool.execute(()->{
                //輸出執行緒的名字
                System.out.println(Thread.currentThread().getName());
            });
        }
        //使用完成後需要進行關閉
        threadPool.shutdown();

    }
}

執行結果:

package pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * study01
 *
 * @author : xgj
 * @description : de
 * @date : 2020-09-21 10:18
 **/
public class ThreadPool {
    public static void main(String[] args) {
        //建立個數動態新增的執行緒池,其數量可以達到Integer.MAX_VALUE
        ExecutorService threadPool = Executors.newCachedThreadPool();
        for (int i = 0; i <10 ; i++) {
            threadPool.execute(()->{
                //輸出執行緒的名字
                System.out.println(Thread.currentThread().getName());
            });
        }
        //使用完成後需要進行關閉
        threadPool.shutdown();

    }
}

執行結果:

但是實際開發中最好不要通過Executors建立,而是自己通過ThreadPoolExecutor建立,這樣可以自定義設定引數,策略。