zoukankan      html  css  js  c++  java
  • 模拟一个死锁

    场景描述

    1.有两个对象锁A1、A2

    2.两个线程t1、t2

    3.t1的执行顺序是A1-->A2, t2的执行顺序是A2-->A1

    4.出现状态 t1持有 A1 锁,等待 A2 锁; t2 持有 A2 锁,等待 A1 锁

    5.出现死锁

    检查死锁方法:使用jps查看线程pid,用jstack pid查看线程运行情况

    代码演示

    DeadLock

    package com.dwz.concurrency.chapter8;
    
    public class DeadLock {
        private OtherService otherService;
        private final Object LOCK = new Object();
    
        public DeadLock(OtherService otherService) {
            this.otherService = otherService;
        }
        
        public void m1() {
            synchronized(LOCK) {
                System.out.println("m1--" + Thread.currentThread());
                otherService.s1();
            }
        }
        
        public void m2() {
            synchronized(LOCK) {
                System.out.println("m2--" + Thread.currentThread());
            }
        }
        
    }

    OtherService

    package com.dwz.concurrency.chapter8;
    
    public class OtherService {
        private DeadLock deadLock;
        private final Object LOCK = new Object();
        
        public void setDeadLock(DeadLock deadLock) {
            this.deadLock = deadLock;
        }
        
        public void s1() {
            synchronized (LOCK) {
                System.out.println("s1========" + Thread.currentThread());
            }
        }
        
        public void s2() {
            synchronized (LOCK) {
                System.out.println("s2========" + Thread.currentThread());
                deadLock.m2();
            }
        }
    }
        

    测试类

    package com.dwz.concurrency.chapter8;
    
    public class DeadLockTest {
    
        public static void main(String[] args) {
            OtherService otherService = new OtherService();
            DeadLock deadLock = new DeadLock(otherService);
            otherService.setDeadLock(deadLock);
            
            new Thread() {
                @Override
                public void run() {
                    while(true) {
                        deadLock.m1();
                    }
                }
            }.start();
            
            new Thread() {
                @Override
                public void run() {
                    while(true) {
                        otherService.s2();
                    }
                }
            }.start();
        }
    
    }

    结果:没有异常信息,程序阻塞

  • 相关阅读:
    North North West
    HDU-5387 Clock
    HDU-1036 Average is not Fast Enough!
    Growling Gears
    HDU-5375 Gray code
    HDU-5373 The shortest problem
    hdu-5364 Distribution money
    UVA
    HDU-5363 Key Set
    HDU-5326 Work
  • 原文地址:https://www.cnblogs.com/zheaven/p/12059807.html
Copyright © 2011-2022 走看看