java线程安全之死锁

java线程安全之死锁,第1张

java线程安全之死锁 死锁图解

 

死锁代码演示
package DeadLock;



public class DeadLockDemo {

    public static void main(String[] args) {
        Object a1 = new Object();
        Object a2 = new Object();

        MyThread t1 = new MyThread(a1, a2);
        MyThread t2 = new MyThread(a2, a1);

        t1.start();
        t2.start();
    }

}

class MyThread extends Thread {

    private Object a1;
    private Object a2;

    public MyThread(Object a1, Object a2) {
        this.a1 = a1;
        this.a2 = a2;
    }

    @Override
    public void run() {
        synchronized (a1) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (a2) {

            }
        }
    }
}
在开发中应该怎么解决线程安全问题

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5582354.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存