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();
//指定无界队列
/*
* ThreadPoolExecutor(
int
corePoolSize, 核心线程数即初始化时的线程数
*
int
maximumPoolSize, 最大线程数
* long keepAliveTime, 存活时间
* TimeUnit unit, 单位
* BlockingQueue 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();
}
}
}