美文网首页
Java 死锁的造成

Java 死锁的造成

作者: 探索的码易 | 来源:发表于2020-05-19 10:27 被阅读0次
  1. java 的死锁有点像相对而行走在独木桥的人,占用当前资源,又等待着另一个资源,并且是多个任务互相占用;
    代码案例:
public static void main(String[] args) {
    final Object a = new Object();
    final Object b = new Object();
    Thread threadA = new Thread(new Runnable() {
        public void run() {
            synchronized (a) {
                try {
                    System.out.println("now i in threadA-locka");
                    Thread.sleep(1000l);
                    synchronized (b) {
                        System.out.println("now i in threadA-lockb");
                    }
                } catch (Exception e) {
                    // ignore
                }
            }
        }
    });

    Thread threadB = new Thread(new Runnable() {
        public void run() {
            synchronized (b) {
                try {
                    System.out.println("1");
                    Thread.sleep(1000l);
                    synchronized (a) {
                        System.out.println("2");
                    }
                } catch (Exception e) {
                    // ignore
                }
            }
        }
    });

    threadA.start();
    threadB.start();
}

如果想要解决相关死锁的问题:
1 顺序执行
2 多个对象资源占用
3 lock 释放资源

相关文章

网友评论

      本文标题:Java 死锁的造成

      本文链接:https://www.haomeiwen.com/subject/wlyvohtx.html