话不多说,上代码!
public class DeadLock{
public static final String A = "A";
public static final String B = "B";
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread1 begin");
synchronized (A){
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (B){}
}
System.out.println("thread1 end");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread2 begin");
synchronized (B){
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (A){}
}
System.out.println("thread2 end");
}
}).start();
}
}
其实就是分别两个线程同时锁住A和B这两个变量,然后sleep个几秒后再各去获取另外的变量,由于变量都给锁住还没释放,所有就造成死锁。