当前位置:网站首页>Thread pool

Thread pool

2022-06-23 16:03:00 weixin_ forty-three million seven hundred and sixty-six thousan

1. Thread pool summary

 Insert picture description here

public static void main(String[] args) throws InterruptedException {
    
        
        //======================== Fixed length ==========================
        ExecutorService ftp =  Executors.newFixedThreadPool(2);
        //newFixedThreadPool The constructor used 
        /* public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }*/
        
        //======================== Caching ==========================
        ExecutorService ctp = Executors.newCachedThreadPool();
        //newCachedThreadPool The constructor used 
       /* public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }*/
       
        //======================== timing ==========================
        ScheduledExecutorService stp = Executors.newScheduledThreadPool(2);
        //newScheduledThreadPool The constructor used 
       /* public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); }*/
       
        //======================== Single case ==========================
        ExecutorService ste = Executors.newSingleThreadExecutor();
        //newSingleThreadExecutor The constructor used 
        /*public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }*/
    }

2. Blocking and non blocking queues

 Insert picture description here

//============================== Non blocking queues ===============================
        ConcurrentLinkedQueue<String> clq = new ConcurrentLinkedQueue<>();
        // The team 
        clq.add("a");
        clq.add("b");
        clq.add("c");
        // View queue headers 
        String peek = clq.peek();
        System.out.println("peek = " + peek);//a
        System.out.println("clq.size() = " + clq.size());//3
        // Out of the team 
        String poll = clq.poll();
        System.out.println("poll = " + poll);//a
        System.out.println("clq.size() = " + clq.size());//2
        System.out.println("=================================");

//====================== Blocking queues =======================================
        BlockingQueue<String> bq = new LinkedBlockingDeque<>(2);
         // bq.add("a");
         //bq.add("b");
         // bq.add("c");//java.lang.IllegalStateException: Deque full
        //todo:offer  and  add The same is to join the team , however offer You can wait a certain time to see if you can insert 
        bq.offer("a");
        bq.offer("b");
        System.out.println("bq.poll() = " + bq.poll());
        // Blocking 3 second , Let's see if we can handle it c Put it in line 
        bq.offer("c",3, TimeUnit.SECONDS);

        System.out.println("bq.poll() = " + bq.poll());
        System.out.println("bq.poll() = " + bq.poll());
                                            // Blocking 5 second , Wait to see if there are any elements that can be extracted 
        System.out.println("bq.poll() = " + bq.poll(5,TimeUnit.SECONDS));

2. Thread pool principle

 Insert picture description here

3. Thread pool testing and analysis

 public static void main(String[] args){
    
        ExecutorService es = Executors.newCachedThreadPool();
        // Using a borderless queue , Let's create a thread with a task 
       /*  Create threads as needed ,  But the thread pool of previously constructed threads will be reused when available .  These pools typically improve the performance of programs that perform many short-term asynchronous tasks .  call execute ( If available ) The previously constructed threads are reused .  If no existing thread is available , A new thread will be created and added to the pool .  Unused 60 Seconds of thread will terminate and be removed from the cache .  So keep it idle long enough that the pool doesn't consume any resources */
        /* public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }*/
        for (int i = 0; i < 100; i++) {
    
            es.execute(()-> System.out.println(Thread.currentThread().getName()));
        }
        es.shutdown();

        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
       /*  Create a thread pool ,  The thread pool can reuse a fixed number of threads ,  Operate on a shared borderless queue .  At any time , most {nThreads} Threads will be active processing tasks .  If other tasks are submitted while all threads are active ,  Then they will wait in the queue , Until the thread is available .  If any thread terminates before shutting down due to a failure during execution , If a new thread is required, it will perform subsequent tasks instead .  Threads in the pool will exist , Until clearly shutdown*/
        /*public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }*/
        for (int i = 0; i < 100; i++) {
    
            fixedThreadPool.execute(()-> System.out.println(Thread.currentThread().getName()));
        }
        fixedThreadPool.shutdown();


        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2);
        /* Create a thread pool , This thread pool can schedule commands to run after a given delay or execute periodically . @param corePoolSize Number of threads to keep in the pool even when idle */
         /*public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); }*/
        for (int i = 0; i < 100; i++) {
    
            //delay(3): Delay three seconds to execute the task 
             scheduledThreadPool.schedule(()-> System.out.println(Thread.currentThread().getName()),3,TimeUnit.SECONDS);
            //initialDelay(2) : Delay time before the first execution  period(1)  The time interval between successive executions 
            //scheduledThreadPool.scheduleAtFixedRate(()-> System.out.println(Thread.currentThread().getName()),2,1,TimeUnit.SECONDS);
        }
        scheduledThreadPool.shutdown();


        ExecutorService singlePool = Executors.newSingleThreadExecutor();
        /* Create one using a single worker Thread operation the executor of an unbounded queue . ( But please note , If the single thread terminates due to a failure in the execution process before the shutdown ,  If follow-up tasks are required , There will be a new replacement .) The task of is to ensure the sequential execution of ,  And no more than one task will be active at any given time .  Equivalent to others newFixedThreadPool(1) The returned execution guarantees that there is no need to reconfigure to use other threads .*/
       /* public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }*/
        for (int i = 0; i < 100; i++) {
    
            singlePool.execute(()-> System.out.println(Thread.currentThread().getName()));
        }
        singlePool.shutdown();
    }

原网站

版权声明
本文为[weixin_ forty-three million seven hundred and sixty-six thousan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231525149105.html