線程連接池

第一種:Executors.newCacheThreadPool():可緩存線程池,先查看池中有沒有以前建立的線程,如果有,就直接使用。如果沒有,就建一個新的線程加入池中,緩存型池子通常用於執行一些生存期很短的異步型任務

package testfordemo;

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

/**
 * Executors.newCacheThreadPool():可緩存線程池,先查看池中有沒有以前建立的線程,如果有,就直接使用。
 * 如果沒有,就建一個新的線程加入池中,緩存型池子通常用於執行一些生存期很短的異步型任務
 */
public class ThreadPoolExecutorTest {

     public static void main(String[] args) {
         //創建一個可緩存線程池
          ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
          for (int i = 0; i < 10; i++) {
         try {
          //sleep可明顯看到使用的是線程池裏面以前的線程,沒有創建新的線程
             Thread.sleep(1000);
          } catch (InterruptedException e) {
          e.printStackTrace();
          }
          cachedThreadPool.execute(new Runnable() {
                 public void run() {
          //打印正在執行的緩存線程信息
           System.out.println(Thread.currentThread().getName()+"正在被執行");
            }
             });
          }

 }
}

線程池爲無限大,當執行當前任務時上一個任務已經完成,會複用執行上一個任務的線程,而不用每次新建線程 

第二種:Executors.newFixedThreadPool(int n):創建一個可重用固定個數的線程池,以共享的無界隊列方式來運行這些線程

package testfordemo;

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


/**
 * Executors.newFixedThreadPool(int n):創建一個可重用固定個數的線程池,以共享的無界隊列方式來運行這些線程
 */
public class ThreadPoolExecutorTest2 {
    public static void main(String[] args) {
        //創建一個可重用固定個數的線程池
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++) {
            fixedThreadPool.execute(new Runnable() {
                public void run() {
                    try {
                        //打印正在執行的緩存線程信息
                        System.out.println(Thread.currentThread().getName()+"正在被執行");
                        Thread.sleep(2000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}

第三種:Executors.newScheduledThreadPool(int n):創建一個定長線程池,支持定時及週期性任務執行 

package testfordemo;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ThreadPoolExecutorTest3 {
    public static void main(String[] args) {
        //創建一個定長線程池,支持定時及週期性任務執行——延遲執行
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
        //延遲1秒執行
        System.out.println(System.currentTimeMillis());
        scheduledThreadPool.schedule(new Runnable() {
            public void run() {
                System.out.println(System.currentTimeMillis());
                System.out.println("延遲1秒執行");
            }
        }, 1, TimeUnit.SECONDS);
    }
}
public void demo2(){
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
        //延遲1秒後每3秒執行一次
        System.out.println(System.currentTimeMillis());
        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
            public void run() {
                System.out.println(System.currentTimeMillis());
                System.out.println("延遲1秒執行每3秒執行一次");
            }
        }, 1,3, TimeUnit.SECONDS);
    }

 第四種:Executors.newSingleThreadExecutor():創建一個單線程化的線程池,它只會用唯一的工作線程來執行任務,保證所有任務按照指定順序(FIFO, LIFO, 優先級)執行。

package testfordemo;

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

public class ThreadPoolExecutorTest4 {
    public static void main(String[] args) {
        //創建一個單線程化的線程池
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            singleThreadExecutor.execute(new Runnable() {
                public void run() {
                    try {
                        //結果依次輸出,相當於順序執行各個任務
                        System.out.println(Thread.currentThread().getName()+"正在被執行,打印的值是:"+index);
                        Thread.sleep(1000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}

第五種(擴展): 緩衝隊列BlockingQueue和自定義線程池ThreadPoolExecutor

1. 緩衝隊列BlockingQueue簡介:

          BlockingQueue是雙緩衝隊列。BlockingQueue內部使用兩條隊列,允許兩個線程同時向隊列一個存儲,一個取出操作。在保證併發安全的同時,提高了隊列的存取效率。

2. 常用的幾種BlockingQueue:

  • ArrayBlockingQueue(int i):規定大小的BlockingQueue,其構造必須指定大小。其所含的對象是FIFO順序排序的。

  • LinkedBlockingQueue()或者(int i):大小不固定的BlockingQueue,若其構造時指定大小,生成的BlockingQueue有大小限制,不指定大小,其大小有Integer.MAX_VALUE來決定。其所含的對象是FIFO順序排序的。

  • PriorityBlockingQueue()或者(int i):類似於LinkedBlockingQueue,但是其所含對象的排序不是FIFO,而是依據對象的自然順序或者構造函數的Comparator決定。

  • SynchronizedQueue():特殊的BlockingQueue,對其的操作必須是放和取交替完成。

自定義線程池,可以用ThreadPoolExecutor類創建,它有多個構造方法來創建線程池。常見的構造函數:ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)

 

package testfordemo;


import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

class TempThread implements Runnable {
    @Override
    public void run() {
        // 打印正在執行的緩存線程信息
        System.out.println(Thread.currentThread().getName() + "正在被執行");
        try {
            // sleep一秒保證3個任務在分別在3個線程上執行
            Thread.sleep(1000);
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class TestThreadPoolExecutor {
    public static void main(String[] args) {
        // 創建數組型緩衝等待隊列
        BlockingQueue<Runnable> bq = new ArrayBlockingQueue<Runnable>(10);
        // ThreadPoolExecutor:創建自定義線程池,池中保存的線程數爲3,允許最大的線程數爲6
        ThreadPoolExecutor tpe = new ThreadPoolExecutor(3, 6, 50, TimeUnit.MILLISECONDS, bq);
        // 創建3個任務
        Runnable t1 = new TempThread();
        Runnable t2 = new TempThread();
        Runnable t3 = new TempThread();
        /*Runnable t4 = new TempThread();
        Runnable t5 = new TempThread();
        Runnable t6 = new TempThread();*/
        // 3個任務在分別在3個線程上執行
        tpe.execute(t1);
        tpe.execute(t2);
        tpe.execute(t3);
        /*tpe.execute(t4);
        tpe.execute(t5);
        tpe.execute(t6);*/
        // 關閉自定義線程池
        tpe.shutdown();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章