gpt4 book ai didi

Java 线程工厂 : Why does one use of works but other doesn't?

转载 作者:行者123 更新时间:2023-11-29 04:52:26 25 4
gpt4 key购买 nike

在以下程序中,代码在 second() 方法中尝试对 Future 执行 get() 时挂起!这是为什么?两个执行器服务之间的唯一区别是它们使用的 ThreadFactory。我使用 newSingleThreadExecutor 还是 newFixedThreadPool 计数为 1 都没有关系。

package me.test;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;

public class ExecutorServiceTest {
ThreadFactory tf1 = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = Executors.defaultThreadFactory().newThread(r);
t.setDaemon(true);
t.setName("tf1-thread");
return t;
}
};
ThreadFactory tf2 = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread("tf2-thread");
t.setDaemon(true);
return t;
}
};
ExecutorService service1 = Executors.newSingleThreadExecutor(tf1);
ExecutorService service2 = Executors.newSingleThreadExecutor(tf2);
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return 0;
}
};

public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorServiceTest executorTest = new ExecutorServiceTest();
executorTest.first(); // this returns
executorTest.second(); // this hangs
System.exit(0);
}

void first() throws ExecutionException, InterruptedException {
Future<Integer> future = service1.submit(callable);
int result = future.get();
System.out.println("result=" + result);
}
void second() throws ExecutionException, InterruptedException {
Future<Integer> future = service2.submit(callable);
int result = future.get();
System.out.println("result=" + result);
}
}

最佳答案

您的第一个工厂创建一个运行指定可运行对象的线程:

Thread t = Executors.defaultThreadFactory().newThread(r);

而在您的第二个工厂中,您只是忘记了向创建的线程提供可运行对象:

Thread t = new Thread("tf2-thread");

因此,在您的第二种情况下,runnable 永远不会运行,因此 future 永远不会获得值(value)。

将第二种情况的线程创建改成

Thread t = new Thread(r, "tf2-thread");

关于Java 线程工厂 : Why does one use of works but other doesn't?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34917923/

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