JDK线程池执行任务排队过程理解

大概就是下面这种思路

import java.util.concurrent.atomic.AtomicInteger;

public class MythreadPool2 {
	AtomicInteger currenPoolSize = new AtomicInteger(0);
	int corePoolSize = 5;
	int taskQueue = 0;
	public  void excute(){
		//并发的时候有可能大于5个线程调用方法跑进了第一个if
		if(currenPoolSize.get() < corePoolSize){
			//第二个if进来的全部进行先自增,多个线程共享一个资源currenPoolSize,因为AtomicInteger时原子性的唯一的
			//当有五个currenPoolSize(0-4各+1都满足其他就进不了第二个if内部),当剩下的线程抢到currenPoolSize为5时经第二个if自增+1,
			//会变成6就会跑到else里减1,所以最终currenPoolSize即为5
			if(currenPoolSize.incrementAndGet() <= corePoolSize ){
				System.out.println("进来咯。。。。"+currenPoolSize.get());
			
				return;
			}else{
				
				System.out.println("执行减操作。。。。"+currenPoolSize.decrementAndGet());
			}
		}
		//因为上面的第二个if满足条件的就五个都return不会执行进行++taskQueue;剩下的没return的15个全部就会执行++taskQueue;
		//最终实现排队
		++taskQueue;

	}
	public static void main(String[] args) throws InterruptedException {
		
		MythreadPool2 mytest = new MythreadPool2();
		for(int i = 0; i < 20; i++){
			new Thread(){
				public void run(){
					System.out.println(Thread.currentThread().getName());
					mytest.excute();
					
				}
				
			}.start();
			
		}
		Thread.sleep(5000);
                //打印出来是5
		System.out.println("最后线程池当前数量"+mytest.currenPoolSize.get());
                //打印出来是15
		System.out.println("最后等待排队的"+mytest.taskQueue);
		
	}
}	

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值