package src.deadLock;
/**
* @author Vince
* @create 2024-07-04-10:21
*/
public class Test {
static StringBuilder str1 = new StringBuilder();
static StringBuilder str2 = new StringBuilder();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread() {
@Override
public void run() {
super.setName("线程1");
System.out.println(Thread.currentThread().getName());
synchronized (str1) {
str1.append(1);
str2.append('a');
try {
Thread.sleep(8);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (str2) {
str1.append(2);
str2.append('b');
}
}
}
};
Thread t2 = new Thread() {
@Override
public void run() {
super.setName("线程2");
System.out.println(Thread.currentThread().getName());
synchronized (str2) {
str1.append(3);
str2.append('c');
synchronized (str1) {
str1.append(4);
str2.append('d');
}
}
}
};
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("str1 ----> " + str1);
System.out.println("str2 ----> " + str2);
}
}
t1 执行 取得 s1 的引用,后休眠
t2 执行 取得 s2 的引用,但此时 s1在 t1 现成未闲置,导致 t1 和 t2 互相拿着对方的钥匙、谁都无法打开 第二个锁。
package src.deadLock;
/**
* @author Vince
* @create 2024-07-04-12:50
*/
public class Test25 extends Thread {
static A a = new A();
static B b = new B();
void init() throws InterruptedException {
Thread.currentThread().setName("main");
b.bar(a);
}
@Override
public void run() {
Thread.currentThread().setName("second");
try {
a.foo(b);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws InterruptedException {
Test25 test25 = new Test25();
Test25 test26 = new Test25();
test25.start();
test26.init();
}
}
//public class Test25 implements Runnable {
// A a = new A();
// B b = new B();
//
// void init() throws InterruptedException {
// Thread.currentThread().setName("main");
// b.bar(a);
// }
//
// @Override
// public void run() {
// Thread.currentThread().setName("second");
// try {
// a.foo(b);
// } catch (InterruptedException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static void main(String[] args) throws InterruptedException {
// Test25 test25 = new Test25();
//
//
// Thread t = new Thread(test25);
//
// t.start();
//
// test25.init();
//
//
// }
//
//}
class A {
synchronized void foo(B b) throws InterruptedException {
System.out.println("AA " + Thread.currentThread().getName());
// Thread.sleep(1000);
b.last();
}
synchronized void last() {
System.out.println("AA LAST");
}
}
class B {
synchronized void bar(A a) throws InterruptedException {
System.out.println("BB " + Thread.currentThread().getName());
a.last();
}
synchronized void last() {
System.out.println("BB LAST");
}
}