[英]Java ThreadFactory: Why does one use of works but other doesn't?
In the following program the code hangs while trying to do get()
on the Future
in the method second()
! 在下面的程序中,代码在尝试在方法second()
对Future
执行get()
时挂起! Why is that? 这是为什么? The only difference between the two executor services are the ThreadFactory
they use. 两个执行程序服务之间的唯一区别是它们使用的ThreadFactory
。 It doesn't matter if I use newSingleThreadExecutor
or newFixedThreadPool
with count of 1. 如果我使用newSingleThreadExecutor
或newFixedThreadPool
并且计数为1则newFixedThreadPool
。
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);
}
}
Your first factory creates a thread that runs the specified runnable: 您的第一个工厂创建一个运行指定的runnable的线程:
Thread t = Executors.defaultThreadFactory().newThread(r);
Whereas in your second factory you simply forgot to provide the runnable to the created thread: 而在你的第二个工厂,你只是忘了为创建的线程提供runnable:
Thread t = new Thread("tf2-thread");
So, in your second case, the runnable is never run, and so the future never gets a value. 因此,在第二种情况下,runnable永远不会运行,因此未来永远不会获得价值。
Change the thread creation in the second case to 将第二种情况下的线程创建更改为
Thread t = new Thread(r, "tf2-thread");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.