synchronized死锁代码
public class Counter {
static String o1 = "obj1";
static String o2 = "obj2";
public static void main(String[] args) {
Counter counter = new Counter();
counter.add();
counter.dec();
}
public void add() {
new Thread(() -> {
while (true) {
synchronized (o1) { // 取得lockA的锁
System.out.println(1);
try {
Thread.sleep(3000); // 此处期待是给B能锁住机会
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o2) { // 取得lockB的锁
System.out.println(2);
} // 开释lockB的锁
} // 开释lockA的锁
}
}).start();
}
public void dec() {
new Thread(() -> {
while (true) {
synchronized (o2) { // 取得lockB的锁
System.out.println(3);
try {
Thread.sleep(3000); // 此处期待是给B能锁住机会
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o1) { // 取得lockA的锁
System.out.println(4);
} // 开释lockA的锁
} // 开释lockB的锁
}
}).start();
}
}
因为synchronized会造成死锁,所以引入了reentranlock.
发表回复