I have something like this
public static void runThread(Thread t){
ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
threadExecutor.execute(t);
}
if I do Thread.currentThread()
, then I get back weblogic.work.ExecuteThread
or sometimes java.lang.Thread
(I used Weblogic as my AppServer), but if I do
public static void runThread(Thread t){
//ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
//threadExecutor.execute(t);
t.start();
}
then when I dod Thread.currentThread()
, I get back com.my.thread.JSFExecutionThread
, which is the Thread that I passed in and this is what I want. Is there a way to fix so the ExecutorService#execute()
return the correct Thread type like Thread#start()
? The thing is that I want to use ExecutorService, because I want to leverage shutdown()
and shutdownNow()
EDIT
Is there anything wrong with this implementation?
/**
* 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);
}
}
}
Is there anything wrong with this implementation?
Yes.
First, the ExecutorService
manages the lifetime of each Thread
from the time the ThreadFactory
creates it until the executor is done with it... and the punchline, a Thread
is not re-usable, once it has terminated it can not be started.
Second
public Thread newThread(Runnable r) {
if(jsfThread != null){
return jsfThread;
}else{
return new Thread(r);
}
}
This code violates the contract of ThreadFactory.newThread
by not making the Runnable
r
set as the runnable to be executed by the jsfThread
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.