java 死锁

2021-05-01 10:28

阅读:503

标签:package   ati   exce   cpu   java   try   start   bsp   str   

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("执行完成");
    }
}

 

java 死锁

标签:package   ati   exce   cpu   java   try   start   bsp   str   

原文地址:https://www.cnblogs.com/honghong75042/p/13218794.html


评论


亲,登录后才可以留言!