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

    线程池

    为什么需要线程池

    • 经常创建和销毁线程是耗时且不稳定的,很难胜任并发度较高的任务。
    • 可以采用池化方法解决这个问题,提前创建好多个线程,构成一个线程池,使用时直接获取,使用完放回池中,避免了频繁创建销毁的消耗。

    使用线程池

    • JDK5.0提供了线程池相关的API:ExecutorService和Executors
    • ExecutorService:真正的线程池接口。常见子类ThreadPoolExecutor。
    • Executors:工具类,线程池的工厂类,用于创建并返回不同类型的线程池。

    代码实现

    package MultiProcess;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class TestPoll {
        public static void main(String[] args) {
            //1.创建服务,创建线程池
            ExecutorService service = Executors.newFixedThreadPool(10);
    
            //2.执行
            service.execute(new MyThread());
            service.execute(new MyThread());
            service.execute(new MyThread());
            service.execute(new MyThread());
            service.execute(new MyThread());
    
            //3.关闭
            service.shutdown();
        }
    }
    
    class MyThread implements Runnable{
        @Override
        public void run() {
    
            System.out.println(Thread.currentThread().getName());
    
        }
    }
    
    结果
    pool-1-thread-1
    pool-1-thread-2
    pool-1-thread-3
    pool-1-thread-4
    pool-1-thread-5
    
  • 相关阅读:
    [DP] Rod-cutting problem
    Dynamic Programming (DP) 问题总结
    [CC150] 八皇后问题
    [cc150] 硬币问题
    [cc150] 括号问题
    [CC150] Get all permutations of a string
    让Eclipse使用新版本的JRE
    Java中的数组问题
    慎用递归!
    cocos2d-x 添加背景音乐和音效-SimpleAudioEngine
  • 原文地址:https://www.cnblogs.com/happysml/p/13848685.html
Copyright © 2011-2022 走看看