gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:57:16 25 4
gpt4 key购买 nike

我有这样的东西

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

最佳答案

Is there anything wrong with this implementation?

是的。

首先,ExecutorService 管理每个Thread 的生命周期,从ThreadFactory 创建它到执行程序完成它。 . 有趣的是,Thread 不可重复使用,一旦终止就无法启动。

第二

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

此代码违反了 ThreadFactory.newThread 的约定,因为没有将 Runnable r 设置为由 Runnable 执行>jsfThread.

关于java - ExecutorService.execute() 不返回线程类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17160621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com