代码
public class TestThreadPoolExecutor {
public static void main(String[] args) {
int corePoolSize = 5;
int maximumPoolSize = 10;
long keepAliveTime = 10;
TimeUnit timeUnit = TimeUnit.SECONDS;
BlockingQueue workQueue = new ArrayBlockingQueue<>(5);
ThreadPoolExecutor.AbortPolicy abortPolicy = new ThreadPoolExecutor.AbortPolicy();
ThreadPoolExecutor.CallerRunsPolicy callerRunsPolicy = new ThreadPoolExecutor.CallerRunsPolicy();
ThreadPoolExecutor.DiscardOldestPolicy discardOldestPolicy = new ThreadPoolExecutor.DiscardOldestPolicy();
ThreadPoolExecutor.DiscardPolicy discardPolicy = new ThreadPoolExecutor.DiscardPolicy();
ThreadPoolExecutor executorA = new ThreadPoolExecutor(
corePoolSize, maximumPoolSize, keepAliveTime, timeUnit, workQueue, new NamedThreadFactory("AAAAA"),abortPolicy);
ThreadPoolExecutor executorB = new ThreadPoolExecutor(
corePoolSize, maximumPoolSize, keepAliveTime, timeUnit, workQueue, new NamedThreadFactory("BBBBB"),abortPolicy);
executorA.execute(new Runnable() {
@Override
public void run() {
int i = 1/0;
}
});
executorB.execute(new Runnable() {
@Override
public void run() {
System.out.printf("executorB处理业务");
}
});
executorA.shutdown();
executorB.shutdown();
}
static class NamedThreadFactory implements ThreadFactory {
private final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup threadGroup;
private final AtomicInteger threadNumber = new AtomicInteger(1);
public final String namePrefix;
NamedThreadFactory(String name) {
SecurityManager s = System.getSecurityManager();
threadGroup = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
if (null == name || "".equals(name.trim())) {
name = "pool";
}
namePrefix = name + "-" +
poolNumber.getAndIncrement() +
"-thread-";
}
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(threadGroup, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
}
结果