栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

线程池的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

线程池的使用

线程和数据库连接这些资源都是非常宝贵的资源。那么每次需要的时候创建,不需要的时候销毁,是非常浪费资源的。那么我们就可以使用缓存的策略,也就是使用线程池。

public class ThreadPoolTest {
    //1、不用线程池
    //函数式接口实现,重写run
    public static void noPool(){

        Runnable target=()->{
            for (int i=0;i<10;i++){
                System.out.println(Thread.currentThread().getName()+":"+i);
            }
        };
        //手动创建两个线程并启动
        //传入一个Runnable实例作为target
        new Thread(target).start();
        new Thread(target).start();


    }
    //2、使用线程池
    public static void usePool(){
        //不需要自己创建线程,只需要创建线程池,将target(要执行的任务)提交给线程池,线程池就会分配两个空闲的线程来执行
        ExecutorService pool= Executors.newFixedThreadPool(6);
        Runnable target=()->{
            for (int i=0;i<10;i++){
                System.out.println(Thread.currentThread().getName()+":"+i);
            }
        };
        //向线程池提交两个线程
        pool.submit(target);
        pool.submit(target);
        //关闭线程池
        pool.shutdown();
    }
    public static void main(String[] args) {
        noPool();
        usePool();
    }
}


Thread-1:0
Thread-1:1
Thread-1:2
Thread-0:0
Thread-1:3
Thread-0:1
Thread-1:4
Thread-0:2
Thread-1:5
Thread-0:3
Thread-1:6
Thread-1:7
Thread-0:4
Thread-0:5
Thread-0:6
Thread-1:8
Thread-0:7
Thread-0:8
Thread-1:9
Thread-0:9
pool-1-thread-2:0
pool-1-thread-1:0
pool-1-thread-2:1
pool-1-thread-1:1
pool-1-thread-2:2
pool-1-thread-1:2
pool-1-thread-2:3
pool-1-thread-1:3
pool-1-thread-2:4
pool-1-thread-1:4
pool-1-thread-2:5
pool-1-thread-1:5
pool-1-thread-2:6
pool-1-thread-1:6
pool-1-thread-2:7
pool-1-thread-1:7
pool-1-thread-2:8
pool-1-thread-1:8
pool-1-thread-2:9
pool-1-thread-1:9


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/631496.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号