ExecutorService.execute()不返回线程类型

时间:2013-06-18 04:37:02

标签: java multithreading executorservice

我有类似的东西

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);
        }
    }
}

1 个答案:

答案 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。