线程死锁小demo

死锁就是:

               a线程 使用a锁 然后在使用b锁

              b线程 使用b锁 然后在使用a锁

 

 

要是a线程执行到a锁的时候  想要调用b锁,而这时b线程执行b锁之后想要调用a锁,因为相互的锁都有在用,这就导致了相互等待锁用完的情况,然后因为锁又各自在用,是用不完的,这就导致了死锁。以下是代码示例:

 

主线程调用 testSS方法

 private void testSS() {
        Object a = new Object();
        Object b = new Object();
        MyCounter counter = new MyCounter(a, b);
        AThread aThread = new AThread(counter);
        BThread bThread = new BThread(counter);
        aThread.start();
        bThread.start();
    }

class MyCounter {
    Object lockA, lockB;
    int n = 0;
    int m = 0;

    public MyCounter(Object lockA, Object lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    public void add() {
        synchronized (lockB) {
            int a = (int) (Math.random() * 10);
            n += a;
            System.out.println("add当前线程:" + Thread.currentThread());
            synchronized (lockA) {
                int aa = (int) (Math.random() * 10);
                m += aa;
                System.out.println("add当前线程:" + Thread.currentThread());
            }
        }
    }

    public void dec() {
        synchronized (lockA) {
            int a = (int) (Math.random() * 10);
            n -= a;
            System.out.println("dec当前线程:" + Thread.currentThread());
            synchronized (lockB) {
                int aa = (int) (Math.random() * 10);
                m -= aa;
                System.out.println("dec当前线程:" + Thread.currentThread());
            }
        }
    }
}






class AThread extends Thread {
    MyCounter c;
    int n = 1000;

    public AThread(MyCounter c) {
        this.c = c;
    }

    @Override
    public void run() {
//        while (n > 0) {
            c.add();
//            try {
//                Thread.sleep(100);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            c.dec();
            System.out.println("athread:" + c.m);
            System.out.println("athread:" + c.n);
            n--;
//        }

    }
}

class BThread extends Thread {
    MyCounter c;
    int n = 1000;

    public BThread(MyCounter c) {
        this.c = c;
    }

    @Override
    public void run() {
//        while (n > 0) {
            c.dec();
//            try {
//                Thread.sleep(100);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            c.add();
            System.out.println("bthread:" + c.m);
            System.out.println("bthread:" + c.n);
            n--;
//        }

    }

}

执行结果:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值