package com.company;
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
// Executors.newCachedThreadPool(); //创建一个缓冲池,缓冲池容量大小为Integer.MAX_VALUE
// Executors.newSingleThreadExecutor(); //创建容量为1的缓冲池
// Executors.newFixedThreadPool(int); //创建固定容量大小的缓冲池
// 任务缓存队列及排队策
// ArrayBlockingQueue:基于数组的先进先出队列,此队列创建时必须指定大小;
// LinkedBlockingQueue:基于链表的先进先出队列,则默认为Integer.MAX_VALUE;
// synchronousQueue:不保存提交的任务,而是将直接新建一个线程来执行新来的任务。
// 线程池容量的动态调整
// setCorePoolSize:设置核心池大小
// setMaximumPoolSize:设置线程池最大能创建的线程数目大小
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
// ThreadPoolExecutor executor = new ThreadPoolExecutor(5,20,200,
// TimeUnit.MINUTES,new LinkedBlockingDeque<Runnable>());
for (int i = 0;i<100;i++) {
MyTask task = new MyTask(i);
executor.execute(task);
System.out.println("线程池中线程数目:"+executor.getPoolSize()+",队列中等待执行的任务数目:"+
executor.getQueue().size()+",已执行玩别的任务数目:"+executor.getCompletedTaskCount());
}
executor.shutdown();
}
}
class MyTask implements Runnable {
//
private int taskId;
MyTask(int num) {
this.taskId = num;
}
@Override
public void run() {
try {
Thread.currentThread().sleep(4000);
System.out.println("taskId:" + taskId);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
网友评论