java 多线程(ThreadPoolExecutor (补充))

import java.util.concurrent.ArrayBlockingQueue;

import java.util.concurrent.ThreadPoolExecutor;

import java.util.concurrent.TimeUnit;





public class App {

    

    private ThreadPoolExecutor threadpool;

    

    public App(){

        /*参数依次是:

        corePoolSize     - 池中所保存的线程数,包括空闲线程。

        maximumPoolSize - 池中允许的最大线程数。

        keepAliveTime     - 当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间。

        unit             - keepAliveTime 参数的时间单位。

        workQueue         - 执行前用于保持任务的队列。此队列仅由保持 execute 方法提交的 Runnable 任务。

        handler         - 由于超出线程范围和队列容量而使执行被阻塞时所使用的处理程序。*/

        

        //规则:

        //1. 池中线程数量小于corePoolSize, 即使存在空闲线程,也启动新线程处理新任务;

        //2. 池中显成熟等于corePoolSize,则添加至workQueue;

        //3. 若此时连workQueue也满,但线程数小于maximumPoolSize, 则添加新线程处理新任务;

        //4. 若超过maximumPoolSize 则调用handler 处理

        //   DiscardOldestPolicy -> 放弃最末的处理请求   

        threadpool = new ThreadPoolExecutor(2,3, 10, TimeUnit.

                SECONDS, new ArrayBlockingQueue(2),

                new ThreadPoolExecutor.DiscardOldestPolicy());

    }

    

    public void subMit(final int value){

        threadpool.execute(new Runnable(){



            @Override

            public void run() {

                try {

                    Thread.sleep(1000);

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

                System.out.print(value + "_hello\r\n");

            }    

        });

    }

    

    public void shutdown() {  

       threadpool.shutdown();  

    } 

    

    

    /**

     * @param args

     */

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        App app = new App();

        for(int i = 0; i < 5;i++){

            app.subMit(i);

        }

        //输出:当threadpool = new ThreadPoolExecutor(2,3, 10, TimeUnit.

        //SECONDS, new ArrayBlockingQueue(1), 

        //3_hello

        //1_hello

        //0_hello

        //4_hello

        

        //输出:当threadpool = new ThreadPoolExecutor(2,3, 10, TimeUnit.

        //SECONDS, new ArrayBlockingQueue(2), 

        //0_hello

        //1_hello

        //4_hello

        //3_hello

        //2_hello

            

        app.shutdown();

    }



}

 

你可能感兴趣的:(java 多线程(ThreadPoolExecutor (补充)))