我有类似的东西
public static void runThread(Thread t){
ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
threadExecutor.execute(t);
}
如果我Thread.currentThread()
,那么我会回来weblogic.work.ExecuteThread
或有时java.lang.Thread
(我使用Weblogic作为我的AppServer),但如果我这样做
public static void runThread(Thread t){
//ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
//threadExecutor.execute(t);
t.start();
}
然后当我点头Thread.currentThread()
时,我回到com.my.thread.JSFExecutionThread
,这是我传入的线程,这就是我想要的。有没有办法解决,所以ExecutorService#execute()
返回正确的线程类型,如Thread#start()
?问题是我想使用ExecutorService,因为我想利用shutdown()
和shutdownNow()
编辑
此实施有什么问题吗?
/**
* Run {@code Runnable runnable} with {@code ExecutorService}
* @param runnable {@code Runnable}
* @return
*/
public static ExecutorService runThread(Thread t){
ExecutorService threadExecutor = Executors.newSingleThreadExecutor(
new ExecutionThreadFactory(t));
threadExecutor.execute(t);
return threadExecutor;
}
private static class ExecutionThreadFactory implements ThreadFactory{
private JSFExecutionThread jsfThread;
ExecutionThreadFactory(Thread t){
if(t instanceof JSFExecutionThread){
jsfThread = (JSFExecutionThread)t;
}
}
@Override
public Thread newThread(Runnable r) {
if(jsfThread != null){
return jsfThread;
}else{
return new Thread(r);
}
}
}
答案 0 :(得分:2)
此实施有什么问题吗?
是
首先,ExecutorService
管理Thread
创建它之前的每个ThreadFactory
的生命周期,直到遗嘱执行者完成它......和一句话{{1}不可重复使用,一旦终止就无法启动。
第二
Thread
此代码违反了public Thread newThread(Runnable r) {
if(jsfThread != null){
return jsfThread;
}else{
return new Thread(r);
}
}
的合同,未将ThreadFactory.newThread
Runnable
设置为r
执行的runnable。