死锁图解

java线程安全之死锁_java

 

死锁代码演示

package DeadLock;

/**
* 死锁代码要会写
* 一般面试官要求你会写。
* 只有会写的,才会在以后开发中注意这个事儿
* 因为死锁很难调试
*/

public class DeadLockDemo {

public static void main(String[] args) {
Object a1 = new Object();
Object a2 = new Object();

MyThread t1 = new MyThread(a1, a2);
MyThread t2 = new MyThread(a2, a1);

t1.start();
t2.start();
}

}

class MyThread extends Thread {

private Object a1;
private Object a2;

public MyThread(Object a1, Object a2) {
this.a1 = a1;
this.a2 = a2;
}

@Override
public void run() {
synchronized (a1) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (a2) {

}
}
}
}

在开发中应该怎么解决线程安全问题

java线程安全之死锁_ide_02