gpt4 book ai didi

java - 多线程 newSingleThreadExecutor 饥饿死锁

转载 作者:行者123 更新时间:2023-11-30 04:34:31 30 4
gpt4 key购买 nike

这直接来自 Java 并发实践。以下情况会导致死锁:

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() 并打印检索到的 header ,那么它是如何死锁的?

最佳答案

您的代码中没有死锁,JVM 不会关闭,因为它有工作线程 - 用于 exec 服务的执行器线程(在 ThreadDeadlock 中定义)。如果添加

exec.shutdown();

RenderPageTaskreturn之前,程序将在所有任务完成后终止。

关于java - 多线程 newSingleThreadExecutor 饥饿死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13815258/

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