码迷,mamicode.com
首页 > 其他好文 > 详细

死锁必须synchronize套synchronize

时间:2015-04-03 14:53:26      阅读:335      评论:0      收藏:0      [点我收藏+]

标签:

package com.Thread;
 
public class DeathSynchronized {
       public static void main(String[] args) {
             //资源
            Object g = new Object();
            Object m = new Object();
             //创建线程
            Test1 t1 = new Test1(g,m);
            Test2 t2 = new Test2(g,m);
            Thread proxy = new Thread(t1);
            Thread proxy2 = new Thread(t2);
             //启动线程
            proxy.start();
            proxy2.start();
      }
}
 
class Test1 implements Runnable {
      Object goods ;
      Object money ;
       public Test1(Object goods, Object money) {
             this.goods = goods;
             this.money = money;
      }
 
       @Override
       public void run() {
             while(true ) {
                   try {
                        test();
                  } catch (Exception e) {
                        e.printStackTrace();
                  }
            }
      }
      
       public void test(){
             synchronized(goods ){
                   try {
                        Thread. sleep(1000);
                  } catch (InterruptedException e) {
                        e.printStackTrace();
                  }
                   synchronized(money ){
                  }
                  System. out.println("一挥手交钱、、、、" );
            }
      }
      
}
class Test2 implements Runnable {
      Object goods ;
      Object money ;
       public Test2(Object goods, Object money) {
             this.goods = goods;
             this.money = money;
      }
 
       @Override
       public void run() {
             while(true ) {
                   try {
                         test();
                  } catch (Exception e) {
                        e.printStackTrace();
                  }
            }
      }
      
       public void test (){
             synchronized(money ){
                   try {
                        Thread. sleep(5000);
                  } catch (InterruptedException e) {
                        e.printStackTrace();
                  }
                   synchronized(goods ){
                        
                  }
                  System. out.println("一挥手交huo、、、、" );
            }
      }
      
}

死锁必须synchronize套synchronize

标签:

原文地址:http://www.cnblogs.com/king-/p/4389732.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!