gpt4 book ai didi

java - 死锁困惑

转载 作者:行者123 更新时间:2023-12-02 06:14:00 25 4
gpt4 key购买 nike

public class SimpleDeadlock implements Runnable{

static SimpleDeadlock sc1=null;
static SimpleDeadlock sc2=null;

void access(SimpleDeadlock sc){

if(Thread.currentThread().getName().equals("Thread1"))
threadMethod1(sc);
if(Thread.currentThread().getName().equals("Thread2"))
threadMethod2(sc);
}

public synchronized void threadMethod1(SimpleDeadlock sc) {

System.out.println(Thread.currentThread().getName()+": threadMethod1");
try{
Thread.sleep(1000);
}
catch(InterruptedException ie){}
sc.deadlock();
}

public synchronized void threadMethod2(SimpleDeadlock sc) {

System.out.println(Thread.currentThread().getName()+": threadMethod2");
try{
Thread.sleep(1000);
}
catch(InterruptedException ie){}
sc.deadlock();
}

synchronized void deadlock() {
System.out.println("In deadlock...");
}

public void run(){
if(Thread.currentThread().getName().equals("Thread1"))
access(sc1);
if(Thread.currentThread().getName().equals("Thread2"))
access(sc2);
}

public static void main(String[] args) throws InterruptedException{

sc1=new SimpleDeadlock();
sc2=new SimpleDeadlock();
Thread thread1=new Thread(sc1);
Thread thread2=new Thread(sc2);
thread1.setName("Thread1");
thread2.setName("Thread2");
thread1.start();
thread2.start();
Thread.sleep(10000);
System.out.println(thread1.getName()+":"+thread1.getState());
System.out.println(thread2.getName()+":"+thread2.getState());
}
}

当我在运行方法中的访问方法中交换对象时,此示例会发生死锁,因为线程 1 等待线程 2 完成,反之亦然。但当它处于给定状态时,它不会陷入僵局。为什么?当thread1调用同步方法threadMethod1()时,对象sc1被锁定。那么在该方法中锁定对象sc1如何调用另一个同步方法。

最佳答案

Java 中的锁是可重入的。如果一个线程已经获取了锁并尝试再次获取它,就不会有任何问题。

关于java - 死锁困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21646113/

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