线程池的优点简介说明

杨采妮 Java面经 发布时间:2022-05-28 23:04:14 阅读数:5842 1
下文笔者讲述使用线程池的优点简介说明,如下所示:
由于创建线程需要消耗资源和时间,所以我们才将创建线程进行池化,
使线程个数控制在合理的范围

为了避免创建线程中消耗资源,当程序启动后,则创建指定数量的线程,我们将这个创建的线程,并称之为“线程池”
例:
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());
    }
}

版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaMianJing/202205/16537502933547.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者