手撕死锁

public Class DeadLockedDemo{

            pubilc static Object resource1 =new Object ();

            public static Object resource2 =new Object ();

            public static void main (String[ ] args){

                new Thread( () ->{

                         synchronized(resource1){

                                    system.out.println(Thread.currentThread() +"get resource1 ");

                                    try{

                                            Thread.sleep(1000);

                                    }catch(InterruptedException e){

                                            e.printStackTrace();

                                     }

                                    system.out.println(Thread.currentThread() +"waiting get resource2 ");       

                                    synchronized(resource2){                        

                                            system.out.println(Thread.currentThread() +"get resource2");

                                    }

                        }

                },"线程1").start();

                new Thread( () ->{

                            synchronized(resource2){

                                        system.out.println(Thread.currentThread() +"get resource 2");

                                        try{

                                              Thread.sleep(1000);

                                         }catch(InterruptedException e){

                                                e.printStackTrace();

                                        }

                                        system.out.println(Thread.currentThread() +"waiting get resource 1");   

                                        synchronized(resource1){

                                                system.out.println(Thread.currentThread() +"get resource 1");

                                        }                                     

                             }

                } ,"线程2").start();             

            }

}


输出

Thread[线程 1,5,main]get resource1

Thread[线程 2,5,main]get resource2

Thread[线程 1,5,main]waiting get resource2

Thread[线程 2,5,main]waiting get resource1


线程 A 通过 synchronized (resource1) 获得 resource1 的监视器锁,然后通过Thread.sleep(1000);让线程 A 休眠 1s 为的是让线程 B 得到执行然后获取到 resource2 的监视器锁。线程 A 和线程 B 休眠结束了都开始企图请求获取对方的资源,然后这两个线程就会陷入互相等待的状态,这也就产生了死锁。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。