gpt4 book ai didi

Java,线程死锁?

转载 作者:行者123 更新时间:2023-11-29 10:10:02 25 4
gpt4 key购买 nike

我的一个 friend 向我展示了他下面的代码,我认为这两个线程可能会死锁,因为它们在尝试获取不同变量的锁时可能会死锁:sb1sb2

当我运行代码时,它们似乎没有死锁,因为我能够看到输出:

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();
}

那么这两个线程会不会死锁呢?

最佳答案

您发布的代码有一个潜在的死锁。如果它运行成功,那就意味着你很幸运。

为了演示潜在的死锁,您可以操纵时间以确保发生死锁。

public static void main(String[] args) {
final StringBuilder sb1 = new StringBuilder();
final StringBuilder sb2 = new StringBuilder();

new Thread() {
public void run() {
synchronized (sb1) {
sb1.append("A");
System.out.println("Thread 1 has sync sb1");
try { Thread.sleep(700); }
catch (InterruptedException e) { e.printStackTrace(); return; }
System.out.println("Waiting for thread 1 to sync sb2");
synchronized (sb2) {
sb2.append("B");
System.out.println(sb1.toString());
System.out.println(sb2.toString());
}
}
}
}.start();

new Thread() {
public void run() {
try { Thread.sleep(500); }
catch (InterruptedException e) { e.printStackTrace(); return; }
synchronized (sb2) {
System.out.println("Thread 2 has sync sb2");
sb2.append("A");
System.out.println("Waiting for thread 2 to sync sb1");
synchronized (sb1) {
sb1.append("B");
System.out.println("second thread: " + sb1.toString());
System.out.println("second thread: " + sb2.toString());
}
}
}
}.start();
}

现在第一个线程肯定会在sb1上同步,第二个线程会在sb2上同步,然后就会出现死锁。

输出:

Thread 1 has sync sb1
Thread 2 has sync sb2
Waiting for thread 2 to sync sb1
Waiting for thread 1 to sync sb2

关于Java,线程死锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43323164/

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