public class DeadLock {
private Integer a = 0;
private Integer b = 0;
private void createDeadLock() {
Runnable first = () -> {
for (int i = 0; i < 100000; i++) {
synchronized(this.a) {
System.out.println("锁住 a");
this.a++;
synchronized(this.b) {
this.b++;
}
System.out.println("对 a、b 的处理完成:" + a + " " + b);
}
}
};
Runnable second = () -> {
for (int i = 0; i < 100000; i++) {
synchronized(this.b) {
System.out.println("锁住 b");
this.b++;
synchronized(this.a) {
this.a++;
}
System.out.println("对 a、b 的处理完成:" + a + " " + b);
}
}
};
Thread firstThread = new Thread(first);
Thread secondThread = new Thread(second);
firstThread.start();
secondThread.start();
}
public static void main(String[] args) {
DeadLock deadLock = new DeadLock();
deadLock.createDeadLock();
}
}