0
点赞
收藏
分享

微信扫一扫

JUC:10_1线程池学习:池化技术的产生、线程池的好处、线程池三大方法

杰森wang 2022-03-30 阅读 62

JUC:10线程池:池化技术的产生

池化技术的产生

程序的运行,会占用系统资源,资源的创建和销毁十分耗时。因此为了避免不停的开关,产生了池化技术,池就是事先准备好一些资源,使用的时候直接拿来用即可,用完之后再返回池,下一个继续使用,完成资源的复用。

常见的池: 线程池、数据库连接池、内存池、对象池

线程池的好处

  1. 降低资源的消耗
  2. 提高响应速度
  3. 方便管理线程
  4. 控制最大并发数,防止内存泄漏

线程池学习需要掌握的:三大方法、7大参数、四种拒绝策略

线程池三大方法:Executors工具类三大方法

实现线程池有三种方法,创建线程池有四种方法。

package executor;

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

/**
 * Executors工具类三大方法
 */
public class Test {

    public static void main(String[] args) {

//        ExecutorService threadPool = Executors.newFixedThreadPool(3);//固定线程数量的线程池
        /**
         * pool-1-thread-3...
         * pool-1-thread-1...
         * pool-1-thread-2...
         * pool-1-thread-2...
         * pool-1-thread-2...
         * pool-1-thread-1...
         * pool-1-thread-3...
         * pool-1-thread-3...
         * pool-1-thread-1...
         * pool-1-thread-2...
         */

//        ExecutorService threadPool = Executors.newSingleThreadExecutor();//只有一个线程的线程池
        /**
         * pool-1-thread-1...
         * pool-1-thread-1...
         * pool-1-thread-1...
         * pool-1-thread-1...
         * pool-1-thread-1...
         * pool-1-thread-1...
         * pool-1-thread-1...
         * pool-1-thread-1...
         * pool-1-thread-1...
         * pool-1-thread-1...
         */

        ExecutorService threadPool = Executors.newCachedThreadPool();//弹性线程池,CPU越高可以达到越多
        /**
         * pool-1-thread-1...
         * pool-1-thread-5...
         * pool-1-thread-6...
         * pool-1-thread-4...
         * pool-1-thread-3...
         * pool-1-thread-2...
         * pool-1-thread-7...
         * pool-1-thread-9...
         * pool-1-thread-8...
         * pool-1-thread-2...
         */

        try {
            for (int i = 0; i < 10; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "...");
                });
            }
        } finally {
            threadPool.shutdown();//线程池关闭,一般放在finally里面执行
        }
    }
}
举报

相关推荐

0 条评论