在以下程序中,代码在方法get()
中Future
上尝试second()
时会挂起!这是为什么?两个执行程序服务之间的唯一区别是它们使用的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);
}
}
答案 0 :(得分:3)
您的第一个工厂创建一个运行指定的runnable的线程:
Thread t = Executors.defaultThreadFactory().newThread(r);
而在你的第二家工厂,你只是忘了为创建的线程提供runnable:
Thread t = new Thread("tf2-thread");
所以,在你的第二种情况下,runnable永远不会运行,因此未来永远不会得到一个值。
将第二种情况下的线程创建更改为
Thread t = new Thread(r, "tf2-thread");