【发布时间】:2016-10-25 13:18:19
【问题描述】:
我正在尝试找出下面提到的代码背后的原因。在这里,如果我使用匿名内部类创建线程,它会进入死锁状态,但使用 lambda 表达式它可以正常工作。我试图找出这种行为背后的原因,但我找不到。
public class ThreadCreationTest {
static {
new ThreadCreationTest();
}
private void call() {
System.out.println("Hello guys!!!");
}
public ThreadCreationTest() {
// when we use this thread it goes in deadlock kind of state
Thread thread1 = new Thread(new Runnable() {
public void run() {
call();
}
});
// This one works fine.
Thread thread = new Thread(() -> call());
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String... args) {
System.out.println("Code finished...");
}
}
带有 lambda 表达式输出:
Hello guys!!!
Code finished...
使用匿名类:
code goes into deadlock state
【问题讨论】:
-
在其他人进入
java.util.concurrent.Callable兔子洞之前,即使您将call重命名为xcall或类似名称,它仍然会发生。 -
非常好的谜题;)我可以给你提示,在调用方法中删除私有访问修饰符将解决问题,但我对此只有一个模糊的解释。
标签: java multithreading lambda java-8 anonymous-class