线程池基本知识

合理利用线程池能够带来三个好处。

  1. 降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的消耗。
  2. 提高响应速度。当任务到达时,任务可以不需要等到线程创建就能立即执行。
  3. 第三:提高线程的可管理性。

corePoolSize(线程池的基本大小):当提交一个任务到线程池时,线程池会创建一个线程来执行任务,即使其他空闲的基本线程能够执行新任务也会创建线程,等到需要执行的任务数大于线程池基本大小时就不再创建。如果调用了线程池的prestartAllCoreThreads方法,线程池会提前创建并启动所有基本线程。

线程池基本工作流程

image-20220415153950535

首先用ThreadpoolExecutor创建一个新的线程池

image-20220415115331397

首先,当任务到达时,运行的线程数<corepoolsize,会新建线程,

如果运行的线程数>=corepoolsize,线程会进入队列,而不添加新的线程

若队列是new ArrayBlockingQueue<>()有界队列,当队列满了之后,再有新的任务到达,此时还没到达maximumpoolsize,就会新建线程,运行任务

有界队列

ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(1);

image-20220415154227311

无界队列

LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>();  

对于无届队列来说,

newFixedThreadPool和newSingleThreadExecutor底层用的是无届队列

image-20220415153235058

image-20220415153135109

特殊的队列

package cn.zlq.SynchronousQueue;

import java.util.concurrent.SynchronousQueue;

/**
 * @ Author     :zhaolengquan.
 * @ Date       :Created in 14:34 2022/4/15
 * @ Description:
 */
public class Test {
	public static void main(String[] args) throws InterruptedException {
		SynchronousQueue<Integer> queue = new SynchronousQueue<>();
		Thread thread1 = new Thread(() -> {
			System.out.println("put thread start");
			try {
				queue.put(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("put thread end");
		});

		Thread thread2 = new Thread(() -> {
			System.out.println("take thread start");
			try {
				System.out.println("take from putThread: " + queue.take());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("take thread end");
		});
		thread1.start();
		Thread.sleep(1000);
		thread2.start();

	}
}

先看结果

put线程执行后就被阻塞了,只有消息被消费后,put线程才可以返回.

image-20220415144100161

默认是非公平 也即是栈结构,公平模式下用的是队列结构

底层实现请前往博客

https://blog.csdn.net/yanyan19880509/article/details/52562039

image-20220415161017018

newCachedThreadPool底层用的就是这个队列

image-20220415152819279

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值