gpt4 book ai didi

java - 试图在两个线程之间创建死锁

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

通过访问线程中的打印方法在两个线程之间创建死锁。我使用了循环屏障,以便两个线程同时启动。如果我是正确的,我的打印方法没有花费时间,因此它被两个线程共享并且不会导致死锁。

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class TWOTHREADDEADLOCLK {

static int b =0;
synchronized static void print()
{

System.out.println(Thread.currentThread().getName() + " " + b);
}
synchronized static int getb()
{
print();
return b;
}

synchronized static void updateb()
{
print();
b=b+10;
}
public static void main(String[] args) {

final CyclicBarrier bar = new CyclicBarrier(2);
Thread thread1 = new Thread(new Runnable(){

@Override
public void run()
{
try {
bar.await();

Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch ( BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
while(true)
print();

}

});
Thread thread2 = new Thread(new Runnable(){

@Override
public void run()
{try {
bar.await();
} catch (InterruptedException | BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
while(true)
getb();

}

});
thread1.start();
thread2.start();
}
}

最佳答案

你不能用单一障碍制造死锁。死锁背后的想法是有(至少)两个线程,每个线程持有不同的锁并试图锁定另一个线程。例如,考虑这个简单的例子:

public class TwoLockRunnable implements Runnable {

private Lock lockInConstructor;
private Lock lockInRuntime;

public TwoLockThread(Lock lockInConstructor, Lock lockInRuntime) {
this.lockInConstructor = lockInConstructor;
this.lockInRuntime = lockInRuntime;

this.lockInConstructor.lock();
}

@Override
public void run() {
lockInRuntime.lock();

System.out.println("After the lock in run()");
}

public static void main(String[] args) {
Lock lock1 = new ReentrantLock();
Lock lock2 = new ReentrantLock();

TwoLockRunnable runnable1 = new TwoLockThread(lock1, lock2);
TwoLockRunnable runnable2 = new TwoLockThread(lock2, lock1);

new Thread(runnable1).start();
new Thread(runnable2).start();
}
}

第一个线程在其构造函数中锁定lock1,第二个线程在其构造函数中锁定lock2。然后第一个线程在运行时尝试锁定 lock2 - 但它不能,因为锁定由另一个线程持有。同样,第二个线程在运行时尝试锁定 lock1,但由于同样的原因而失败。因此,您会遇到死锁,消息 “After the lock in run()” 永远不会被打印出来。

关于java - 试图在两个线程之间创建死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39932025/

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