死锁就是:一个宝藏需要两把钥匙来打开,同时间正好来了两个人,他们一人一把钥匙,但是双方都再等对方能交出钥匙来打开宝藏,谁都没交出自己的那把钥匙.就这样这俩人一直僵持下去,直到开发人员发现这个局面.
public class ThreadTest implements Runnable {
private int trainCount = 100;
private final Object lock = new Object();
public boolean flag;
@Override
public void run() {
while (true) {
if (flag) {
synchronized (lock) {
sell1();
System.out.println(Thread.currentThread().getName() + " 拿到lock锁");
}
} else {
sell1();
}
}
}
public synchronized void sell1() {
System.out.println(Thread.currentThread().getName() + " 拿到this锁");
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + " 拿到lock锁");
if (trainCount > 0) {
System.out.println(Thread.currentThread().getName() + " Sell a ticket:" + (100 - trainCount + 1));
trainCount--;
}
}
}
public static void main(String[] args) {
ThreadTest threadTest = new ThreadTest();
Thread thread = new Thread(threadTest, "窗口①");
Thread thread2 = new Thread(threadTest, "窗口②");
thread.start();
threadTest.flag = true;
thread2.start();
}
}
上面代码就是一个死锁
导致死锁的原因在于
线程①先拿到同步函数的this锁,在拿到同步代码块中的lock锁
线程②先拿到同步代码块中的lock锁,在拿到同步函数的this锁
互补释放锁导致的
解决死锁的方法:
不要嵌套同步代码块