java 死锁

时间:2020-07-01 14:29:33   收藏:0   阅读:40
package test;

public class LockExer {
    private static String lockA="locka";
    private static String lockB="lockb";

    public void methodA() throws Exception {
        synchronized (lockA){
            System.out.println("我是A方法获取锁A:"+Thread.currentThread().getName());
            // 让出CPU执行权,但是不释放锁
            Thread.sleep(1000);
            synchronized (lockB){
                System.out.println("我是A方法获取锁B:"+Thread.currentThread().getName());
            }
        }
    }
    public void methodB() throws Exception {
        synchronized (lockB){
            System.out.println("我是B方法获取锁B:"+Thread.currentThread().getName());
            // 让出CPU执行权,但是不释放锁
            Thread.sleep(1000);
            synchronized (lockA){
                System.out.println("我是B方法获取锁A:"+Thread.currentThread().getName());
            }
        }
    }

    public static void main(String[] args) {
        LockExer lockExer = new LockExer();
        new Thread(()->{
            try {
                lockExer.methodA();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            try {
                lockExer.methodB();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        System.out.println("执行完成");
    }
}

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!