Java,线程陷入僵局? [英] Java, threads deadlocked?
问题描述
我的一个朋友在下面向我展示了他的代码,我认为这两个线程可能会死锁,因为它们在尝试获取不同变量的锁时可能会死锁: sb1
和 sb2
。
One of my friends showed me his code below, and I thought the two threads could be deadlocked, because they could deadlock while trying to acquire locks on the different variables: sb1
and sb2
.
运行代码时,它们似乎没有死锁,因为我能够看到输出:
When I run the code, they don't seem to be deadlocked, as I was able to see the output:
A
B
second thread: AB
second thread: BA
以下代码:
public static void main(String[] args) {
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
new Thread() {
public void run() {
synchronized (sb1) {
sb1.append("A");
synchronized (sb2) {
sb2.append("B");
System.out.println(sb1.toString());
System.out.println(sb2.toString());
}
}
}
}.start();
new Thread() {
public void run() {
synchronized (sb2) {
sb2.append("A");
synchronized (sb1) {
sb1.append("B");
System.out.println("second thread: " + sb1.toString());
System.out.println("second thread: " + sb2.toString());
}
}
}
}.start();
}
那么两个线程是否会陷入僵局?
so could the two threads be deadlocked?
推荐答案
您没有遇到死锁这一事实并不意味着不会发生死锁。
The fact that you are not getting a deadlock does not imply a deadlock cannot occur.
您正确地推断,当两个线程试图以相反的顺序获取两个不同资源上的监视器时,就会发生死锁可能。
You are right in inferring that a deadlock might occur when two threads attempt to acquire monitors on two different resources in opposite orders.
因此,此代码可能产生死锁。
Therefore, this code may produce a deadlock.
但是,如果有的话两个线程中的两个设法先获取两个监视器,不会发生死锁(这似乎是在执行过程中发生的)。
However, if any of the two threads manages to acquire both the monitors before the other, no deadlock will occur (which seems to be happening with your execution).
这里是可能发生死锁的方式:
Here's how a deadlock might occur instead:
- 线程一开始并获得锁定
sb1
- 线程二开始并获得
sb2
的锁定 - 线程一等待获取
sb2
的锁,该锁由线程二拥有 - 线程二等待获取对
sb1
的锁定,该线程归线程一
- Thread one starts and acquires lock on
sb1
- Thread two starts and acquires lock on
sb2
- Thread one waits to acquire lock on
sb2
, which is owned by thread two - Thread two waits to acquire lock on
sb1
, which is owned by thread one
As没有线程会释放其锁,并且两者都在等待对方,您将获得死锁。
As no thread will release its lock and both wait on the other, you get a deadlock.
注意:作为 Khelwood 建议,强制线程进入睡眠状态可能会阻止其中一个线程首先获取两个锁,从而产生死锁。
Note: as Khelwood advises, forcing the threads to sleep may prevent one of the threads from acquiring both locks first, hence producing the deadlock.
这篇关于Java,线程陷入僵局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!