死锁案例分析

本文通过模拟买票场景,展示了如何在多线程环境中产生死锁,并提供了避免死锁的方法。通过具体代码示例,解释了同步代码块的使用及死锁产生的条件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

死锁的产生以及解决办法,看代码分析,注意里边的注释,自行运行。

package thread;

/**
 * 模拟买票
 * 
 * @author yhl
 * 
 */

class Thread02 implements Runnable{
    private static int countTraket = 100;
    public boolean flag = true;
    private  Object mutex  = new Object();
    @Override
    public void run() {
        if (flag) {
            while (true) {
                synchronized (mutex) {
                    // 锁(同步代码块)在什么时候释放? 代码执行完, 自动释放锁.
                    // 如果flag为true 线程1 先拿到 obj锁,在拿到this 锁、 才能执行。
                    // 如果flag为false 线程2 先拿到this,在拿到obj锁,才能执行。
                    // 死锁的产生:同步中嵌套同步,互不释放。
                    // 死锁解决办法:不要在同步中嵌套同步。
                    sale();
                }
            }
        } else {
            while (true) {
                sale();
            }
        }

    }

    //同步代码块
    public void sale(){
        synchronized(mutex){
            if(countTraket>0){
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("当前线程:"+Thread.currentThread().getName()+";正在买第"+(100-countTraket+1)+"张票。");
                countTraket--;
            }
        }
    }

    //同步函数
    public synchronized void sale1(){
        if(countTraket>0){
            System.out.println("当前线程:"+Thread.currentThread().getName()+";正在买第"+(100-countTraket+1)+"张票。");
            countTraket--;
        }
    }
    public static synchronized void sale2(){
        if(countTraket>0){
            System.out.println("当前线程:"+Thread.currentThread().getName()+";正在买第"+(100-countTraket+1)+"张票。");
            countTraket--;
        }
    }

}
public class ThreadDemo1 {

    public static void main(String[] args) throws InterruptedException {

        Thread02 t  = new Thread02();
        Thread t1 = new Thread(t,"窗口1");
        Thread t2 = new Thread(t,"窗口2");
        t1.start();
        Thread.sleep(50);
        t.flag=false;
        t2.start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值