import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 自定义线程池
*/
public class MyLinkedThreadPool
implements Runnable {
// static 必须得加
private static AtomicInteger
count =
new AtomicInteger(0);
public static void main(String[]
args) throws InterruptedException {
LinkedBlockingQueue queue =
new LinkedBlockingQueue<Runnable>();//指定无界队列
/*
* ThreadPoolExecutor(int corePoolSize,
核心线程数即初始化时的线程数
* int maximumPoolSize,
最大线程数
* long keepAliveTime, 存活时间
* TimeUnit unit, 单位
* BlockingQueue<Runnable> workQueue,任务队列
* ThreadFactory threadFactory, 线程工厂
* RejectedExecutionHandler handler) 拒绝执行的方法(拒绝策略)
*/
/*
* 有界队列corePoolSize,如果线程数小于corePoolSize则会创建线程,
* 到达corePoolSize后不会在继续创建线程,有任务就扔到队列里
* 如果任务创建和处理的速度差异很大,无界队列会保持快速增长,
* 直到内存耗尽宕机
*/
ThreadPoolExecutor pool =
new ThreadPoolExecutor(5,
10,
120L,
TimeUnit.SECONDS,
queue
//ThreadFactory threadFactory,
// RejectedExecutionHandler handler)
);
for (int i=0;
i<20; i++) {
/*
* 提交20个任务
* corePoolSize为5,则先执行5个,剩余15个放入队列,
* 等执行完5个,然后5个5个分批执行
*
*/
pool.execute(new MyLinkedThreadPool());
}
Thread.sleep(1000);
System.out.println("队列size:" +
queue.size());
Thread.sleep(2000);
}
@Override
public void run()
{
int temp =
count.incrementAndGet();
System.out.println("任务:" +
temp);
try {
Thread.sleep(2000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}