• 多线程(死锁)


    线程死锁的原因:

    同步中嵌套同步,但是锁却不同

    死锁演示(DeadLockDemo):

    class Test implements Runnable
    {
        private boolean flag;
        //构造函数中传入标记的值,用来操作run方法中的if else循环
        Test(boolean flag)
        {
            this.flag = flag;
        }
    
        public void run()
        {
            if(flag)
            {
                while(true)
                {
                    synchronized(MyLock.lockA)
                    {
                        System.out.println(Thread.currentThread().getName()+"...if lockA ");
                        synchronized(MyLock.lockB)
                        {
                            System.out.println(Thread.currentThread().getName()+"..if lockB");                    
                        }
                    }
                }
            }
            else
            {
                while(true)
                {
                    synchronized(MyLock.lockB)
                    {
                        System.out.println(Thread.currentThread().getName()+"..else lockB");
                        synchronized(MyLock.lockA)
                        {
                            System.out.println(Thread.currentThread().getName()+".....else lockA");
                        }
                    }
                }
            }
        }
    }
    
    //放置了两个锁
    class MyLock
    {
        static Object lockA = new Object();
        static Object lockB = new Object();
    }
    
    class  DeadLockTest
    {
        public static void main(String[] args) 
        {
            //传入true使其在if循环中
            Thread t1 = new Thread(new Test(true));
            //传入false使其在if循环中
            Thread t2 = new Thread(new Test(false));
            t1.start();
            t2.start();
        }
    }
    DeadLockDemo
  • 相关阅读:
    python实现双向链表
    django contenttypes
    tensorflow学习笔记一
    vue指令和事件绑定
    es6简单介绍
    mysql主从复制
    mysql事务
    winform 使用 ReportViewer做报表
    设置控件获取焦点
    修改安卓串口蓝牙app问题记录
  • 原文地址:https://www.cnblogs.com/gzc911/p/4905892.html
Copyright © 2020-2023  润新知