线程池的优点简介说明
下文笔者讲述使用线程池的优点简介说明,如下所示:
由于创建线程需要消耗资源和时间,所以我们才将创建线程进行池化, 使线程个数控制在合理的范围 为了避免创建线程中消耗资源,当程序启动后,则创建指定数量的线程,我们将这个创建的线程,并称之为“线程池”例:
public class ThreadPool { public static void main(String[] args) { threadDemo(100000); poolDemo(100000); } public static void poolDemo(int count) { long startTime = System.currentTimeMillis(); final list<Integer> l = new LinkedList<>(); ThreadPoolExecutor tp = new ThreadPoolExecutor(1, 10, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(count)); final Random random = new Random(); for (int i = 0; i < count; i++) { Runnable runnable = new Runnable() { @Override public void run() { l.add(random.nextInt()); } }; tp.execute(runnable); } tp.shutdown(); try { tp.awaitTermination(1, TimeUnit.DAYS); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("ThreadPool spend time:" + (System.currentTimeMillis() - startTime)); System.out.println(l.size()); } public static void threadDemo(int count) { long startTime = System.currentTimeMillis(); final List<Integer> l = new LinkedList<>(); final Random random = new Random(); for (int i = 0; i < count; i++) { Thread thread = new Thread(() -> l.add(random.nextInt())); thread.start(); try { Thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Thread spend time:"+(System.currentTimeMillis() - startTime)); System.out.println(l.size()); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。