大概就是下面这种思路
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);
}
}