public class RateLimiterDemo {
public static class DivTask implements Runnable{
int a,b;
public DivTask(int a,int b){
this.a = a;
this.b = b;
}
@Override
public void run(){
double re = a/b;
System.out.println(re);
}
}
public static void main(String[] args) {
ThreadPoolExecutor pools = new TraceThreadPoolExecutor(0,
Integer.MAX_VALUE,
0L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
for(int i =0;i<5;i++)
pools.execute(new DivTask(100,i));
System.out.println(Runtime.getRuntime().availableProcessors());
}
}
public class TraceThreadPoolExecutor extends ThreadPoolExecutor {
public TraceThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue){
super(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue);
}
@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() {
try{
task.run();
} catch (Exception e){
clientStack.printStackTrace();
try {
throw e;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
};
}
}
如果使用线程池,那么错误可能会变得更加常见。
wrap方法得第2个参数为一个异常,里面保存着提交任务得线程堆栈信息。该方法将我们
传入的Runnable任务进行一层包装,使之能处理异常信息。当任务发生异常时,
这个异常会被打印。
本文介绍了如何在Java中使用`ThreadPoolExecutor`实现多线程任务处理,并通过`TraceThreadPoolExecutor`扩展,提供线程堆栈跟踪功能,以便更好地管理线程错误和调试。
1275

被折叠的 条评论
为什么被折叠?



