这直接来自Java Concurrency in Practice。以下导致死锁:
class ThreadDeadlock {
ExecutorService exec = Executors.newSingleThreadExecutor();
public class RenderPageTask implements Callable<String> {
public String call() throws Exception {
Future<String> header, footer;
System.out.println(Thread.currentThread().getName());
header = exec.submit(new LoadFileTask("header.html"));
footer = exec.submit(new LoadFileTask("footer.html"));
//String page = renderBody();
// Will deadlock -- task waiting for result of subtask
//System.out.println("executed header and footer");
String headerS = header.get();
System.out.println("retrieved header");
String footerS = footer.get();
return headerS+ footerS;
}
}
}
class LoadFileTask implements Callable<String>{
String name;
public LoadFileTask(String name) {
super();
this.name = name;
}
@Override
public String call() throws Exception {
/*Scanner s = new Scanner(name);
StringBuilder str = new StringBuilder();
while(s.hasNextLine()){
str.append(s.nextLine());
}*/
System.out.println(Thread.currentThread().getName()+this.name);
return "";
}
}
/* Call from Main */
private static void checkDeadLock(){
ThreadDeadlock.RenderPageTask callable = new ThreadDeadlock().new RenderPageTask();
ExecutorService es = Executors.newFixedThreadPool(1);
es.submit(callable);
es.shutdown();
}
我无法弄清楚为什么这会导致死锁。我已经检查过了。它甚至返回 header.get() 并打印检索到的标题,那么它是如何死锁的?