java 線程池-4種

來源:互聯網
上載者:User

標籤:運行   try   extends   nbsp   import   空閑   current   create   main   

java 有四種線程池

1、可緩衝線程池

newCachedThreadPool
建立一個可緩衝線程池,如果線程池長度超過處理需要,可靈活回收空閑線程,若無可回收

2、定長線程池 可控制最大並發數 

newFixedThreadPool 

建立一個定長線程池,可控制線程最大並發數,超出的線程會在隊列中等待。

package com.zyh.controller.test;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * 學習並發編程 * * @author 1101399 * @CreateDate 2018-7-31 下午2:28:29 */public class ThreadTestTwo {    public static void main(String[] args) {        // 可緩衝線程池        ExecutorService excutorOne = Executors.newCachedThreadPool();        // 定長線程池 可控制最大並發數        ExecutorService excutorTwo = Executors.newFixedThreadPool(2);        StringBuffer nameOne = new StringBuffer("A");        excutorOne.submit(new ThreadOne(nameOne));        StringBuffer nameTwo = new StringBuffer("B");        excutorOne.submit(new ThreadOne(nameTwo));        try {            Thread.sleep(10000);        } catch (InterruptedException e) {            e.printStackTrace();        }        StringBuffer nameThree = new StringBuffer("C");        excutorOne.submit(new ThreadOne(nameThree));        System.out.println("\n*******************************************\n");        excutorTwo.submit(new ThreadOne(nameOne));        excutorTwo.execute(new ThreadOne(nameTwo));        excutorTwo.submit(new ThreadOne(nameThree));        System.out.println("\n*******************************************\n");    }    public static class ThreadOne implements Runnable {        public StringBuffer name;        public ThreadOne(StringBuffer name) {            this.name = name;        }        @Override        public void run() {            for (int i = 0; i < 5; i++) {                System.out.println("ThreadOne name:" + name + " ID:"                        + Thread.currentThread().getId());                try {                    Thread.sleep(500);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }    }}

 

3、單線程化線程池

newSingleThreadExecutor
建立一個單線程化的線程池,它只會用唯一的背景工作執行緒來執行任務,保證所有任務按照指定順序(FIFO, LIFO, 優先順序)執行

package com.zyh.controller.test;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * student threads * * @author 1101399 * @CreateDate 2018-7-30 下午2:09:01 */public class ThreadTestOne {    public static void main(String[] args) throws InterruptedException {        final ThreadTest A1 = new ThreadTest("A1");        final ThreadTest A2 = new ThreadTest("A2");        final ThreadTest A3 = new ThreadTest("A3");        A1.start();        A2.start();        A1.join();        A2.join();        System.out.println("方法一實現多線程");        if (!A1.isAlive()) {// A1 線程不存在的時候控制台列印一條資訊            System.out.println("A1執行完畢?!");        }        final Thread B1 = new Thread(new RunnableTest("B1"));        B1.start();        final Thread B2 = new Thread(new RunnableTest("B2"));        B2.start();        B1.join();        B2.join();        System.out.println("方法二實現多線程");        /**         * 直接實現線程的開闢 FIXME         */        final Thread C1 = new Thread(new Runnable() {            @Override            public void run() {                try {                    A1.join();                    A2.join();                    B1.join();                    B2.join();                } catch (InterruptedException e) {                    e.printStackTrace();                }                for (int i = 0; i < 2; i++) {                    System.out.println("··············");                }            }        });        C1.start();        C1.join();        System.out.println("方法三實現多線程");        System.out.println("線程池的應用");        // 線程池的學習&應用        // 單線程化線程池        ExecutorService executor = Executors.newSingleThreadExecutor();        executor.submit(A1);        executor.submit(A2);        executor.submit(A3);        executor.execute(B1);// 這種樣子的線程類就是不執行        executor.execute(A1);        executor.submit(B1);// 這三種線程的實現方式之前不能 XXX start()啟動線程        executor.submit(B2);// 這三種線程的實現方式之前不能 XXX start()啟動線程        executor.submit(C1);// 這三種線程的實現方式之前不能 XXX start()啟動線程        executor.shutdown();// 停止傳入任務        // executor.shutdownNow();// 停止線程池-對線程池說STOP        // 會導致線程池中第一個線程的sleep出現sleep interrupted異常        // 該函數的核心是:它向該線程發起interrupt()請求,而sleep()方法遇到有interrupt()請求時,會拋出InterruptedException(),並繼續往下執行        // 運行到這條語句直接停止線程池-檢測線程停止後執行的join()函數毫無意義,不能生效    }    /**     * 繼承Thread來實現多線程編程 FIXME     */    public static class ThreadTest extends Thread {        public String nameOne;        public StringBuffer nameTwo;        public StringBuilder nameThree;        private long time;        // 建構函式        public ThreadTest(String name) {            this.nameOne = name;        }        // 建構函式        public ThreadTest(String name, long time) {            this.nameOne = name;            this.time = time;        }        @Override        public void run() {            for (int i = 0; i < 2; i++) {                System.out.println(this.nameOne + " Thread運行第 " + i + " 次!");                try {                    if (this.time != 0) {                        sleep(this.time + i);                        System.out.println(this.nameOne + "-time-" + (time + i));                    } else {                        // sleep((int) Math.random() * 1000);                        sleep(50);                        System.out                                .println(this.nameOne + "-random-" + (int) (Math.random() * 1000));                    }                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }    }    /**     * 實現介面Runnable來實現多線程編程 FIXME     */    public static class RunnableTest implements Runnable {        public String nameOne;        public StringBuffer nameTwo;        public StringBuilder nameThree;        private long time;        public RunnableTest(String name) {            this.nameOne = name;        }        public RunnableTest(String name, long time) {            this.nameOne = name;            this.time = time;        }        @Override        public void run() {            for (int i = 0; i < 2; i++) {                System.out.println(this.nameOne + " Runnable運行第 " + i + " 次!");                try {                    if (this.time != 0) {                        Thread.sleep(this.time + i);                        System.out.println(this.nameOne + "-time-" + (time + i));                    } else {                        Thread.sleep((int) Math.random() * 1000);                        System.out                                .println(this.nameOne + "-random-" + (int) (Math.random() * 1000));                    }                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }    }}

 

4、定長 定時周期性線程池

newScheduledThreadPool
建立一個定長線程池,支援定時及週期性任務執行

 

java 線程池-4種

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.