创建一个覆盖beforeExecute方法的ThreadPoolExecutor。
private final ThreadPoolExecutor executor = new ThreadPoolExecutor (new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()){
protected void beforeExecute(Thread t, Runnable r) {
t.setName(deriveRunnableName(r));
}
protected void afterExecute(Runnable r, Throwable t) {
Thread.currentThread().setName("");
}
protected <V> RunnableFuture<V> newTaskFor(final Runnable runnable, V v) {
return new FutureTask<V>(runnable, v) {
public String toString() {
return runnable.toString();
}
};
};
}
不知道究竟如何derveRunnableName()
会的工作,也许toString()
?
编辑:Thread.currentThread()实际上是在beforeExecute中设置的线程,它调用afterExecute。您可以引用Thread.currentThread(),然后在afterExecute中设置名称。这是在的javadoc
/**
* Method invoked upon completion of execution of the given Runnable.
* This method is invoked by the thread that executed the task. If
* non-null, the Throwable is the uncaught <tt>RuntimeException</tt>
* or <tt>Error</tt> that caused execution to terminate abruptly.
*
* <p><b>Note:</b> When actions are enclosed in tasks (such as
* {@link FutureTask}) either explicitly or via methods such as
* <tt>submit</tt>, these task objects catch and maintain
* computational exceptions, and so they do not cause abrupt
* termination, and the internal exceptions are <em>not</em>
* passed to this method.
*
* <p>This implementation does nothing, but may be customized in
* subclasses. Note: To properly nest multiple overridings, subclasses
* should generally invoke <tt>super.afterExecute</tt> at the
* beginning of this method.
*
* @param r the runnable that has completed.
* @param t the exception that caused termination, or null if
* execution completed normally.
*/
protected void afterExecute(Runnable r, Throwable t) { }
编辑指出的TPE将包装了Runnable一个FutureTask内,所以要支持toString
方法,你可以覆盖newTaskFor
并创建自己的包裹FutureTask。
“同步与Runnable接口保持线程池线程的名称,它实际上是运行” - > Runnable接口/赎回没有定义一个名字,所以我不能完全看到你的问题的重点。你的ThreadFactory是否给每个线程一个不同的名字? – serg10 2011-12-15 16:41:17
对,我的每个Runnables和Callables都实现了一个Named接口,所以我可以访问名称。我意识到我很挑剔,因为我已经为所有Runnables实现了一个特殊功能,但是希望避免添加手动设置线程名称的其他代码。 – 2011-12-15 16:51:19
为了清晰起见编辑,将一些“线程池”更改为“线程”,将一些“线程”更改为“任务”。 – 2011-12-15 17:01:14