zoukankan      html  css  js  c++  java
  • 18.线程池

    频繁创建线程就会大大降低系统的效率,因为频繁创建线程和销毁线程需要时间,那么有没有一种办法使得线程可以复用,就是执行完一个任务,并不被销毁,而是可以继续执行其他的任务?在Java中可以通过线程池来达到这样的效果。

    http://www.cnblogs.com/dolphin0520/p/3932921.html

    https://blog.csdn.net/weixin_28760063/article/details/81266152

    https://blog.csdn.net/xiaojin21cen/article/details/81810534

    https://www.cnblogs.com/jmsjh/p/7762034.html

    https://www.cnblogs.com/dolphin0520/p/3949310.html

    package duoxiancheng;
    
    import java.util.concurrent.ArrayBlockingQueue;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    
    public class Demo4 {
        public static void main(String[] args) {   
            ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 200, TimeUnit.MILLISECONDS,
                    new ArrayBlockingQueue<Runnable>(5));
             
            for(int i=0;i<15;i++){
                MyTask myTask = new MyTask(i);
                executor.execute(myTask);
                System.out.println("线程池中线程数目:"+executor.getPoolSize()+",队列中等待执行的任务数目:"+
                executor.getQueue().size()+",已执行完毕的任务数目:"+executor.getCompletedTaskCount());
            }
            executor.shutdown();
        }
    }
    
    class MyTask implements Runnable {
       private int taskNum;
        
       public MyTask(int num) {
           this.taskNum = num;
       }
        
       @Override
       public void run() {
           System.out.println("正在执行task "+taskNum);
           try {
               Thread.currentThread().sleep(4000);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           System.out.println("task "+taskNum+"执行完毕");
       }
    }
  • 相关阅读:
    POJ 3279 Fliptile
    FZU 2143 Board Game
    【HDU 5015】233 Matrix
    【BZOJ 2463】 谁能赢呢?
    【POJ 2311】 Cutting Game
    【HDU 1846】 Brave Game
    【HDU 1847】 Good Luck in CET-4 Everybody!
    【Codeforces 258D】 Count Good Substrings
    【Codeforces 258B】 Sort the Array
    【Codeforces 258A】 Game With Sticks
  • 原文地址:https://www.cnblogs.com/aaronRhythm/p/12926108.html
Copyright © 2011-2022 走看看