在java程序中怎么造成死锁_java – 了解为什么在此实现中发生死锁

 2023-09-10 阅读 21 评论 0

摘要:我是多线程的新手,我遇到了这个例子:public class TestThread {造成死锁的原因、public static Object Lock1 = new Object();public static Object Lock2 = new Object();public static void main(String args[]) {java死锁产生的原因、ThreadDemo1 T1 =

我是多线程的新手,我遇到了这个例子:

public class TestThread {

造成死锁的原因、public static Object Lock1 = new Object();

public static Object Lock2 = new Object();

public static void main(String args[]) {

java死锁产生的原因、ThreadDemo1 T1 = new ThreadDemo1();

ThreadDemo2 T2 = new ThreadDemo2();

T1.start();

Java死锁,T2.start();

}

private static class ThreadDemo1 extends Thread {

public void run() {

synchronized (Lock1) {

System.out.println("Thread 1: Holding lock 1...");

try { Thread.sleep(10); }

catch (InterruptedException e) {}

System.out.println("Thread 1: Waiting for lock 2...");

synchronized (Lock2) {

System.out.println("Thread 1: Holding lock 1 & 2...");

}

}

}

}

private static class ThreadDemo2 extends Thread {

public void run() {

synchronized (Lock2) {

System.out.println("Thread 2: Holding lock 2...");

try { Thread.sleep(10); }

catch (InterruptedException e) {}

System.out.println("Thread 2: Waiting for lock 1...");

synchronized (Lock1) {

System.out.println("Thread 2: Holding lock 1 & 2...");

}

}

}

}

}

这会导致以下示例输出:

Thread 1: Holding lock 1...

Thread 2: Holding lock 2...

Thread 1: Waiting for lock 2...

Thread 2: Waiting for lock 1...

即,存在僵局.但是,如果我们改变在第二个线程中获得的锁的顺序,那么它现在看起来像这样:

public class TestThread {

public static Object Lock1 = new Object();

public static Object Lock2 = new Object();

public static void main(String args[]) {

ThreadDemo1 T1 = new ThreadDemo1();

ThreadDemo2 T2 = new ThreadDemo2();

T1.start();

T2.start();

}

private static class ThreadDemo1 extends Thread {

public void run() {

synchronized (Lock1) {

System.out.println("Thread 1: Holding lock 1...");

try { Thread.sleep(10); }

catch (InterruptedException e) {}

System.out.println("Thread 1: Waiting for lock 2...");

synchronized (Lock2) {

System.out.println("Thread 1: Holding lock 1 & 2...");

}

}

}

}

private static class ThreadDemo2 extends Thread {

public void run() {

synchronized (Lock1) {

System.out.println("Thread 2: Holding lock 1...");

try { Thread.sleep(10); }

catch (InterruptedException e) {}

System.out.println("Thread 2: Waiting for lock 2...");

synchronized (Lock2) {

System.out.println("Thread 2: Holding lock 1 & 2...");

}

}

}

}

}

它按预期工作,示例输出如下所示:

Thread 1: Holding lock 1...

Thread 1: Waiting for lock 2...

Thread 1: Holding lock 1 & 2...

Thread 2: Holding lock 1...

Thread 2: Waiting for lock 2...

Thread 2: Holding lock 1 & 2...

有人可以向我解释第一个导致死锁的情况,以及为什么第二个代码的更改会修复它?

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/42367.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息