java 实现死锁

Posted 六道对穿肠

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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("now i in threadB-lockb");
                        Thread.sleep(1000l);
                        synchronized (a) {
                            System.out.println("now i in threadB-locka");
                        }
                    } catch (Exception e) {
                        // ignore
                    }
                }
            }
        });

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

第二种写法 思路都一样


public static void miin(String[] args){
    
    final Object lockA = new Object();
    final Object lockB = new Object();
    
    Thread threadA = new Thread(new Runable{
        public void run(){
            synchnaized(lockA){
                Sleep(1000);
                synchnaized(LockB){
                    
                }
            }
        }
    });
    
    Thread threadB = new Thread(new Runable{
        public void run(){
            synchnaized(lockB){
                Sleep(1000);
                synchnaized(LockA){
                    
                }
            }
        }
    });
    
    threadA.start();
    threadB.start();
}

以上是关于java 实现死锁的主要内容,如果未能解决你的问题,请参考以下文章

55行代码实现Java线程死锁

Java_线程同步和死锁

java synchronized 死锁问题

OS学习笔记死锁总结(含银行家算法的实现Java版)

Java多线程-死锁简述

怎么处理JAVA多线程死锁问题?