构造方法:
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,long keepAliveTime, TimeUnit unit,BlockingQueue<Runnable> workQueue,RejectedExecutionHandler handler)
参数解读:
corePoolSize: 线程池维护线程的最少数量
maximumPoolSize:线程池维护线程的最大数量
keepAliveTime: 线程池维护线程所允许的空闲时间
unit: 线程池维护线程所允许的空闲时间的单位
workQueue: 线程池所使用的缓冲队列
handler: 线程池对拒绝任务的处理策略
package com.threadPool;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class MyThreadPool extends ThreadPoolExecutor {
private static MyThreadPool myPool = new MyThreadPool(10, 100, 1,
TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>());
private MyThreadPool(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
public static MyThreadPool getInstance() {
return myPool;
}
}
package com.threadPool;
import java.util.concurrent.CountDownLatch;
public class MainThread {
public static void main(String[] args) {
ThreadExecutor executor = new ThreadExecutor("A", 3);
executor.execute();
}
}
class ThreadExecutor {
private String prefix;
private int size;
public ThreadExecutor(String prefix, int size) {
this.prefix = prefix;
this.size = size;
}
public void execute() {
System.out.println(prefix + " begin.");
ThreadA temp = null;
CountDownLatch cDownLatch = new CountDownLatch(size);
for (int i = 0; i < size; i++) {
temp = new ThreadA(cDownLatch, prefix + i);
MyThreadPool.getInstance().execute(temp);
}
try {
cDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(prefix + " end.");
}
}
package com.threadPool;
import java.util.concurrent.CountDownLatch;
public class ThreadA implements Runnable {
private CountDownLatch cDownLatch;
private String name;
public ThreadA(CountDownLatch cDownLatch, String threadName) {
this.cDownLatch = cDownLatch;
this.name = threadName;
}
@Override
public void run() {
System.out.println(name + " begin.");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + " end.");
cDownLatch.countDown();
}
}