我有一个线程工厂、执行程序、线程类和一个可运行类。这是线程类:(threadsCount 是一个 AtomicInteger,我用它来跟踪创建的线程数)
public void run() {
try {
threadsCount.incrementAndGet();
super.run();
} finally {
threadsCount.decrementAndGet();
}
}
我的可运行类目前没有实现,但有空的 run() 方法。
当我尝试调用 Executor.execute(new RunnableClazz()) 时,控制权来到这个 Thread 类 - run() 方法,当它遇到 super.run() 时,它转到 RunnableClazz#run() 方法。
所有这些都很好。但问题是,在 RunnableClazz#run() 完成后,控件不会回到我的 Thread 类的“finally”块。
有任何想法吗?我是否需要在 run() 方法结束时手动杀死可运行对象?
public class ThreadAA extends Thread {
private static final AtomicInteger threadsCount = new AtomicInteger();
private static final AtomicInteger threadsCreated = new AtomicInteger();
public static final String DEFAULT_NAME = "ThreadAA";
public ThreadAA(Runnable r)
{
this(r, DEFAULT_NAME);
}
public ThreadAA(Runnable r, String threadName)
{
super(r, threadName + "-" + threadsCreated.incrementAndGet());
setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
{
public void uncaughtException(Thread t, Throwable e)
{
logger.error("Uncaught exception in thread " + t.getName(), e);
}
});
}
@Override
public void run()
{
boolean debug = false;
//just for debug purpose
debug = true;
if(debug)
{
logger.debug("Running thread " + getName());
}
try
{
threadsCount.incrementAndGet();
super.run();
}
finally
{
threadsCount.decrementAndGet();
if(debug)
{
logger.debug("Done running thread " + getName());
}
}
}
}
我的可运行类:
public class RunnableClazz implements Runnable {
@Override
public void run() {
logger.debug("Inside RunnableClazz");
}
}
调用这个 runnable 的方法如下所示:
Executor executor = new Executor(25, 100, 1L, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(5), new TFactory("abc"));
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.execute(new RunnableClazz());
executor.execute(new RunnableClazz());
请注意,我在服务器启动期间只创建了一次执行程序。我粘贴它只是为了说明我如何创建它。因此executor.execute(new RunnableClazz());
产生了问题。