Java线程池入门03


1. 这3种创建线程池的方式有风险


  • FixedThreadPool : 固定大小的线程池
  • SingleThreadExecutor : 单个线程的线程池
  • CachedThreadPool : 可缓存的线程池

![[Pasted image 20250224194301.png]]

  • FixedThreadPool内部其实也是使用ThreadPoolExecutor来创建的
    等价于 :
new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

会发现核心线程和最大线程数是一样的,以此铸就了固定大小的线程池。
使用FixedThreadPool

package LearnThreadPool;  
  
import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;  
import java.util.stream.IntStream;  
  
/**  
 * 使用固定大小的线程池  
 *  
 * @author cat  
 * @version 2025/2/24 20:09  
 * @since JDK17  
 */  
public class UseFixedThreadPool {  
    public static void m() {  
        System.out.println(Thread.currentThread().getName());  
    }  
  
    public static void main(String[] args) {  
        // 创建一个大小为10的固定大小的线程池  
        ExecutorService executorService = Executors.newFixedThreadPool(10);  
        IntStream.range(0, 3).forEach(i -> executorService.execute(new Thread(UseFixedThreadPool::m)));  
        executorService.shutdown();  
    }  
}
输出 : 
pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
  • SingleThreadExecutor内部其实也是使用ThreadPoolExecutor来创建的。
    等价于 :
new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

使用SingleThreadExecutor

package LearnThreadPool;  
  
import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;  
import java.util.stream.IntStream;  
  
/**  
 * 使用固定大小的线程池  
 *  
 * @author cat  
 * @version 2025/2/24 20:09  
 * @since JDK17  
 */  
public class UseFixedThreadPool {  
    public static void m() {  
        System.out.println(Thread.currentThread().getName());  
    }  
  
    public static void main(String[] args) {  
        // 创建一个大小为10的固定大小的线程池  
        ExecutorService executorService = Executors.newSingleThreadExecutor();  
        IntStream.range(0, 3).forEach(i -> executorService.execute(new Thread(UseFixedThreadPool::m)));  
        executorService.shutdown();  
    }  
}
输出 : 
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
  • CachedThreadPool内部其实也是使用ThreadPoolExecutor来创建的。
new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
  • FixedThreadPool 和 SingleThreadExecutor 允许的请求队列长度为Integer.MAX_VALUE,可能会堆积大量的请求,从而导致 00M。
  • CachedThreadPool 允许的创建线程数量为 Integer.MAX_VALUE,可能会创建大量的线程,从而导致 00M。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值