0

我有这样的东西

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

1 回答 1

2

这个实现有什么问题吗?

是的。

首先,从创建它到执行器完成它,它ExecutorService管理每个的生命周期......而且妙语 a不可重用,一旦它终止,它就无法启动。ThreadThreadFactoryThread

第二

public Thread newThread(Runnable r) {
    if(jsfThread != null){
        return jsfThread;
    }else{
        return new Thread(r);
    }
}

此代码违反了 的合同,ThreadFactory.newThread因为它没有将Runnable r集合设置为可运行的以由jsfThread.

于 2013-06-18T05:23:00.123 回答