一、扩展 ThreadPoolExecutor
package com.sande.user.utils;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.bouncycastle.jcajce.provider.symmetric.AES.Wrap;
public class TraceThreadPoolExecutor extends ThreadPoolExecutor {
public TraceThreadPoolExecutor(int corePoolSize,int maximumPoolSize,
long keepAlieTime,TimeUnit unit,BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAlieTime, unit, workQueue,threadFactory,handler);
}
@Override
public void execute(Runnable task) {
super.execute(wrap(task,clientTrace(),Thread.currentThread().getName()));
}
@Override
public Future<?> submit(Runnable task) {
return super.submit(wrap(task,clientTrace(),Thread.currentThread().getName()));
}
private Exception clientTrace() {
return new Exception("Client stack trace");
}
private Runnable wrap(final Runnable task,final Exception clientStack,
String clientThreadName) {
return new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
task.run();
} catch (Exception e) {
// TODO: handle exception
clientStack.printStackTrace();
throw e;
}
}
};
}
}
二、创建现场的类
package com.sande.user.utils;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPool {
public static final TraceThreadPoolExecutor executor =
new TraceThreadPoolExecutor(10, 10,10,TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(10),
Executors.defaultThreadFactory(),
//new ThreadPoolExecutor.AbortPolicy()
new ThreadPoolExecutor.CallerRunsPolicy());
}
三、业务类
package com.threadPool;
import com.sande.user.utils.ThreadPool;
public class DivTask implements Runnable {
int a,b;
public DivTask(int a,int b) {
this.a = a;
this.b = b;
}
@Override
public void run() {
try {
double re = a/b;
System.out.println(re);
} catch (Exception e) {
// TODO: handle exception
//e.printStackTrace();
throw e;
}
}
}
四、主类
package com.threadPool;
import com.sande.user.utils.ThreadPool;
public class DivTaskMain {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
//ThreadPool.executor.submit(new DivTask(100, i));
ThreadPool.executor.execute(new DivTask(100, i));
}
}
}
五、参考
实战Java高并发程序设计