说明:
1. 使用无界队列时不会存在任务存入队列失败的情况。当有新的任务到来,系统线程小于coresize则会新建线程执行任务。当达到corsize,就不会在新增线程。若有新的任务来了,若没有新的线程资源则任务直接进入队列进行等待。若任务的创建和和处理任务的线程差异较大,无界队列将会保存快速增长,知道耗尽系统内存。
注意:“10”,maxsize,在无界队列中,该参数可以忽视。
package cm.pool;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class UseTHreadpoolExecutor_2 implements Runnable {
private static AtomicInteger count=new AtomicInteger(0);
@Override
public void run() {
try {
int temp=count.incrementAndGet();
System.out.println(Thread.currentThread().getName()+"-----任务:"+temp);
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
ExecutorService pool = new ThreadPoolExecutor(5, // corePoolSize,
10, // maximumPoolSize,
120l, // keepAliveTime,
TimeUnit.SECONDS, // unit,
queue);
for (int i = 0; i < 20; i++) {
pool.execute(new UseTHreadpoolExecutor_2());
}
Thread.sleep(2000);
System.out.println("queue 容量:"+queue.size());
Thread.sleep(2000);
pool.shutdown();
}
}