java线程池

线程池

背景:经常创建和销毁,使用量特别大的资源,比如并发情况下的线程,对性能影响很大

思路:

  • 提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。
  • 可以避免频繁的创建销毁、实现重复利用

好处:

  • 提高响应速度(减少了创建新线程的时间)
  • 降低资源消耗(重复利用线程池中线程,不需要每次都创建)
  • 便于线程管理
package com.yuanyu.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//测试线程池
public class TestPool {
    public static void main(String[] args) {
        //创建线程池
        ExecutorService service= Executors.newFixedThreadPool(10); //该参数为线程池的大小

        //执行
        service.execute(new Mythead());
        service.execute(new Mythead());
        service.execute(new Mythead());
        service.execute(new Mythead());
        service.execute(new Mythead());

        //关闭
        service.shutdown();
    }
}

class Mythead implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

程序运行结果:

pool-1-thread-1
pool-1-thread-4
pool-1-thread-3
pool-1-thread-2
pool-1-thread-5

posted @   原语  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示