package com.yuan1.day1;
/**
* @author QLBF
* @version 1.0
* @date 2021/6/16 21:15
*/
class A{}
class B{}
public class test5 {
static A a=new A();
static B b=new B();
public static void main(String[] args) throws InterruptedException {
new Thread(()->{
synchronized (a){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (b){
System.out.println("我获得了a和b");
}
}
}).start();
Thread.sleep(1000);
new Thread(()->{
synchronized (b){
synchronized (a){
System.out.println("我获得了b和a");
}
}
}).start();
}
}
下面这个更加简单一点:
package com.yuan.deadlock.v1;
import lombok.extern.slf4j.Slf4j;
@Slf4j(topic = "c.TestDeadLock")
public class TestDeadLock {
public static void main(String[] args) {
test1();
}
private static void test1() {
Object A = new Object();
Object B = new Object();
Thread t1 = new Thread(() -> {
synchronized (A) {
log.debug("A lock A");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (B) {
log.debug("A lock B");
log.debug("操作...");
}
}
}, "t1");
Thread t2 = new Thread(() -> {
synchronized (B) {
log.debug("B lock B");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (A) {
log.debug("B lock A");
log.debug("操作...");
}
}
}, "t2");
t1.start();
t2.start();
}
}
本文详细探讨了Java中线程同步导致的死锁现象,通过`TestDeadLock`和`test5`示例,展示了如何通过synchronized关键字和并发执行引发的资源争夺问题。关键部分涉及了对象锁的使用和线程间的依赖关系,旨在帮助读者理解并发编程中的问题及解决策略。
611

被折叠的 条评论
为什么被折叠?



