死锁

多线程死锁:同步中嵌套同步,导致锁无法释放

模拟死锁的情况:

public class TrainThread implements Runnable {

    // 定义初始化票100张
    private int ticketCount = 100;

    private Object object = new Object();

    public boolean flag = true;

    public void run() {

        if (flag) {
            while (true) {
                synchronized (object) { // 对象锁
                    sale();
                }
            }

        } else {
            while (true) {
                sale();
            }

        }

    }

    private synchronized void sale() { // this锁
        synchronized (object) {
            if (ticketCount > 0) {
                try {
                    Thread.sleep(40);
                } catch (Exception e) {

                }
                System.out.println(Thread.currentThread().getName() + "卖出了第" + (100 - ticketCount + 1 + "张票"));
                ticketCount--;
            }
        }
    }

}
public class App {
    public static void main(String[] args) throws InterruptedException {
        TrainThread trainThread = new TrainThread();
        
        //模拟了两个线程,必须都用同一个Runnable 的子类对象,才能叫 实现资源的共享
        Thread thread1 = new Thread(trainThread);
        Thread thread2 = new Thread(trainThread);
        thread1.start();
        thread1.sleep(40);
        trainThread.flag = false;
        thread2.start();
    }

}

两个线程,线程1 进入 对象锁,然后开始sale(),线程1 占据了this 锁(会放开),占据了对象锁(长期)

线程2 进入了sale(),占据了this 锁,因为对象锁被线程1 占据,所以不能继续执行,同时因为占据了this 锁,线程1 也进入不了,产生死锁

原文地址:https://www.cnblogs.com/pickKnow/p/11017864.html