Java 線程池,java線程池

來源:互聯網
上載者:User

Java 線程池,java線程池

系統啟動一個線程的成本是比較高的,因為它涉及到與作業系統的互動,使用線程池的好處是提高效能,當系統中包含大量並發的線程時,會導致系統效能劇烈下降,甚至導致JVM崩潰,而線程池的最大線程數參數可以控制系統中並發線程數不超過次數。

一、Executors 工廠類用來產生線程池,該工廠類包含以下幾個靜態Factory 方法來建立對應的線程池。建立的線程池是一個ExecutorService對象,使用該對象的submit方法或者是execute方法執行相應的Runnable或者是Callable任務。線程池本身在不再需要的時候調用shutdown()方法停止線程池,調用該方法後,該線程池將不再允許任務添加進來,但是會直到已添加的所有任務執行完成後才死亡。

1、newCachedThreadPool(),建立一個具有緩衝功能的線程池,提交到該線程池的任務(Runnable或Callable對象)建立的線程,如果執行完成,會被緩衝到CachedThreadPool中,供後面需要執行的任務使用。

import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class CacheThreadPool {    static class Task implements Runnable {        @Override        public void run() {            System.out.println(this + " " + Thread.currentThread().getName() + " AllStackTraces map size: "                    + Thread.currentThread().getAllStackTraces().size());        }    }    public static void main(String[] args) {        ExecutorService cacheThreadPool = Executors.newCachedThreadPool();                //先添加三個任務到線程池        for(int i = 0 ; i < 3; i++) {            cacheThreadPool.execute(new Task());        }                //等三個線程執行完成後,再次添加三個任務到線程池        try {            Thread.sleep(3000);        } catch (InterruptedException e) {            e.printStackTrace();        }                for(int i = 0 ; i < 3; i++) {            cacheThreadPool.execute(new Task());        }    }}

執行結果如下:

CacheThreadPool$Task@2d312eb9 pool-1-thread-1 AllStackTraces map size: 7CacheThreadPool$Task@59522b86 pool-1-thread-3 AllStackTraces map size: 7CacheThreadPool$Task@73dbb89f pool-1-thread-2 AllStackTraces map size: 7CacheThreadPool$Task@5795cedc pool-1-thread-3 AllStackTraces map size: 7CacheThreadPool$Task@256d5600 pool-1-thread-1 AllStackTraces map size: 7CacheThreadPool$Task@7d1c5894 pool-1-thread-2 AllStackTraces map size: 7

線程池中的線程對象進行了緩衝,當有新任務執行時進行了複用。但是如果有特別多的並發時,緩衝線程池還是會建立很多個線程對象。

2、newFixedThreadPool(int nThreads) 建立一個指定線程個數,線程可複用的線程池。

import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class FixedThreadPool {    static class Task implements Runnable {        @Override        public void run() {            System.out.println(this + " " + Thread.currentThread().getName() + " AllStackTraces map size: "                    + Thread.currentThread().getAllStackTraces().size());        }    }    public static void main(String[] args) {        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);        // 先添加三個任務到線程池        for (int i = 0; i < 5; i++) {            fixedThreadPool.execute(new Task());        }        // 等三個線程執行完成後,再次添加三個任務到線程池        try {            Thread.sleep(3);        } catch (InterruptedException e) {            e.printStackTrace();        }        for (int i = 0; i < 3; i++) {            fixedThreadPool.execute(new Task());        }    }}

執行結果:

FixedThreadPool$Task@7045c12d pool-1-thread-2 AllStackTraces map size: 7
FixedThreadPool$Task@50fa0bef pool-1-thread-2 AllStackTraces map size: 7
FixedThreadPool$Task@ccb1870 pool-1-thread-2 AllStackTraces map size: 7
FixedThreadPool$Task@7392b4e3 pool-1-thread-1 AllStackTraces map size: 7
FixedThreadPool$Task@5bdeff18 pool-1-thread-2 AllStackTraces map size: 7
FixedThreadPool$Task@7d5554e1 pool-1-thread-1 AllStackTraces map size: 7
FixedThreadPool$Task@24468092 pool-1-thread-3 AllStackTraces map size: 7
FixedThreadPool$Task@fa7b978 pool-1-thread-2 AllStackTraces map size: 7

3、newSingleThreadExecutor(),建立一個只有單線程的線程池,相當於調用newFixedThreadPool(1)

4、newSheduledThreadPool(int corePoolSize),建立指定線程數的線程池,它可以在指定延遲後執行線程。也可以以某一周期重複執行某一線程,知道調用shutdown()關閉線程池。

樣本如下:

import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;public class ScheduledThreadPool {    static class Task implements Runnable {        @Override        public void run() {            System.out.println("time " + System.currentTimeMillis()  + " " + Thread.currentThread().getName() + " AllStackTraces map size: "                    + Thread.currentThread().getAllStackTraces().size());        }    }    public static void main(String[] args) {        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);                scheduledExecutorService.schedule(new Task(), 3, TimeUnit.SECONDS);                scheduledExecutorService.scheduleAtFixedRate(new Task(), 3, 5, TimeUnit.SECONDS);            try {            Thread.sleep(30 * 1000);        } catch (InterruptedException e) {            e.printStackTrace();        }        scheduledExecutorService.shutdown();    }}

運行結果如下:

time 1458921795240 pool-1-thread-1 AllStackTraces map size: 6time 1458921795241 pool-1-thread-2 AllStackTraces map size: 6time 1458921800240 pool-1-thread-1 AllStackTraces map size: 7time 1458921805240 pool-1-thread-1 AllStackTraces map size: 7time 1458921810240 pool-1-thread-1 AllStackTraces map size: 7time 1458921815240 pool-1-thread-1 AllStackTraces map size: 7time 1458921820240 pool-1-thread-1 AllStackTraces map size: 7

由已耗用時間可看出,任務是按照5秒的周期執行的。

5、newSingleThreadScheduledExecutor() 建立一個只有一個線程的線程池,同調用newScheduledThreadPool(1)。

二、ForkJoinPool和ForkJoinTask

ForkJoinPool是ExecutorService的實作類別,支援將一個任務劃分為多個小任務並行計算,在把多個小任務的計算結果合并成總的計算結果。它有兩個建構函式

ForkJoinPool(int parallelism)建立一個包含parallelism個並行線程的ForkJoinPool。

ForkJoinPool(),以Runtime.availableProcessors()方法傳回值作為parallelism參數來建立ForkJoinPool。

ForkJoinTask 代表一個可以並行,合并的任務。它是實現了Future<T>介面的抽象類別,它有兩個抽象子類,代表無傳回值任務的RecuriveAction和有傳回值的RecursiveTask。可根據具體需求繼承這兩個抽象類別實現自己的對象,然後調用ForkJoinPool的submit 方法執行。

RecuriveAction 樣本如下,實現並行輸出0-300的數字。

import java.util.concurrent.ForkJoinPool;import java.util.concurrent.RecursiveAction;import java.util.concurrent.TimeUnit;public class ActionForkJoinTask {    static class PrintTask extends RecursiveAction {        private static final int THRESHOLD = 50;        private int start;        private int end;        public PrintTask(int start, int end) {            this.start = start;            this.end = end;        }        @Override        protected void compute() {            if (end - start < THRESHOLD) {                for(int i = start; i < end; i++) {                    System.out.println(Thread.currentThread().getName() + " " + i);                }            } else {                int middle = (start + end) / 2;                PrintTask left = new PrintTask(start, middle);                PrintTask right = new PrintTask(middle, end);                left.fork();                right.fork();            }        }    }    public static void main(String[] args) {        ForkJoinPool pool = new ForkJoinPool();                pool.submit(new PrintTask(0,  300));        try {            pool.awaitTermination(2, TimeUnit.SECONDS);        } catch (InterruptedException e) {            e.printStackTrace();        }                pool.shutdown();    }}

在拆分小任務後,調用任務的fork()方法,加入到ForkJoinPool中並存執行。

RecursiveTask樣本,實現並行計算100個整數求和。拆分為每20個數求和後擷取結果,在最後合并為最後的結果。

import java.util.Random;import java.util.concurrent.ExecutionException;import java.util.concurrent.ForkJoinPool;import java.util.concurrent.Future;import java.util.concurrent.RecursiveTask;public class TaskForkJoinTask {    static class CalTask extends RecursiveTask<Integer> {        private static final int THRESHOLD = 20;        private int arr[];        private int start;        private int end;        public CalTask(int[] arr, int start, int end) {            this.arr = arr;            this.start = start;            this.end = end;        }        @Override        protected Integer compute() {            int sum = 0;            if (end - start < THRESHOLD) {                for (int i = start; i < end; i++) {                    sum += arr[i];                }                System.out.println(Thread.currentThread().getName() + "  sum:" + sum);                return sum;            } else {                int middle = (start + end) / 2;                CalTask left = new CalTask(arr, start, middle);                CalTask right = new CalTask(arr, middle, end);                left.fork();                right.fork();                return left.join() + right.join();            }        }    }    public static void main(String[] args) {        int arr[] = new int[100];        Random random = new Random();        int total = 0;        for (int i = 0; i < arr.length; i++) {            int tmp = random.nextInt(20);            total += (arr[i] = tmp);        }        System.out.println("total " + total);        ForkJoinPool pool = new ForkJoinPool(4);        Future<Integer> future = pool.submit(new CalTask(arr, 0, arr.length));        try {            System.out.println("cal result: " + future.get());        } catch (InterruptedException e) {            e.printStackTrace();        } catch (ExecutionException e) {            e.printStackTrace();        }        pool.shutdown();    }}

執行結果如下:

total 912ForkJoinPool-1-worker-2  sum:82ForkJoinPool-1-worker-2  sum:123ForkJoinPool-1-worker-2  sum:144ForkJoinPool-1-worker-3  sum:119ForkJoinPool-1-worker-2  sum:106ForkJoinPool-1-worker-2  sum:128ForkJoinPool-1-worker-2  sum:121ForkJoinPool-1-worker-3  sum:89cal result: 912

子任務執行完後,調用任務的join()方法擷取子任務執行結果,再相加獲得最後的結果。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.