package com.test.multithread;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @Package: com.test.multithread
* @ClassName: ThreadPoolTest
* @Description: 类描述
* @Author: bulingfeng
* @CreateDate: 2019/3/1/001 10:50
* 特别感谢 https://www.cnblogs.com/dolphin0520/p/3932921.html 写的不错 整个博客都不错
*/
public class ThreadPoolTest {
public static void main(String[] args) {
//队列的值改为 200 再看下效果 会发现只有队列满了以后才会 创建新线程知道新线程 知道最大的线程数量
ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(5,10,5000, TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(5));
for(int i=0;i<15;i++){
MyTask myTask=new MyTask(i);
threadPoolExecutor.execute(myTask);
System.out.println("线程池中的数量:"+threadPoolExecutor.getPoolSize()+",线程池中已经完成的"+threadPoolExecutor.getCompletedTaskCount()+
"队列中的任务数:"+threadPoolExecutor.getQueue().size());
}
}
}
class MyTask implements Runnable {
private int taskNum;
public MyTask(int num) {
this.taskNum = num;
}
@Override
public void run() {
System.out.println("正在执行task "+taskNum);
try {
Thread.currentThread().sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("task "+taskNum+"执行完毕");
}
}
线程池样例
最新推荐文章于 2024-01-07 09:00:00 发布