Java线程:并发协作-死锁

系统 1588 0
Java线程:并发协作-死锁
 
线程发生死锁可能性很小,即使看似可能发生死锁的代码,在运行时发生死锁的可能性也是小之又小。
 
发生死锁的原因一般是两个对象的锁相互等待造成的。
 
在《Java线程:线程的同步与锁》一文中,简述死锁的概念与简单例子,但是所给的例子是不完整的,这里给出一个完整的例子。
 
/**
* Java线程:并发协作-死锁
*
* @author Administrator 2009-11-4 22:06:13
*/

public class Test {
         public static void main(String[] args) {
                DeadlockRisk dead = new DeadlockRisk();
                MyThread t1 = new MyThread(dead, 1, 2);
                MyThread t2 = new MyThread(dead, 3, 4);
                MyThread t3 = new MyThread(dead, 5, 6);
                MyThread t4 = new MyThread(dead, 7, 8);

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

}

class MyThread extends Thread {
         private DeadlockRisk dead;
         private int a, b;


        MyThread(DeadlockRisk dead, int a, int b) {
                 this .dead = dead;
                 this .a = a;
                 this .b = b;
        }

        @Override
         public void run() {
                dead.read();
                dead.write(a, b);
        }
}

class DeadlockRisk {
         private static class Resource {
                 public int value;
        }

         private Resource resourceA = new Resource();
         private Resource resourceB = new Resource();

         public int read() {
                 synchronized (resourceA) {
                        System.out.println( "read():" + Thread.currentThread().getName() + "获取了resourceA的锁!" );
                         synchronized (resourceB) {
                                System.out.println( "read():" + Thread.currentThread().getName() + "获取了resourceB的锁!" );
                                 return resourceB.value + resourceA.value;
                        }
                }
        }

         public void write( int a, int b) {
                 synchronized (resourceB) {
                        System.out.println( "write():" + Thread.currentThread().getName() + "获取了resourceA的锁!" );
                         synchronized (resourceA) {
                                System.out.println( "write():" + Thread.currentThread().getName() + "获取了resourceB的锁!" );
                                resourceA.value = a;
                                resourceB.value = b;
                        }
                }
        }
}
 
下面死锁的情况发生了,真是难得一见啊:
 
 

本文出自 “ 熔 岩 ” 博客,请务必保留此出处 http://lavasoft.blog.51cto.com/62575/222074

Java线程:并发协作-死锁


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论