synchronized

package dxs;

public class TestMain {  
  
    /**  
     * <p>Description:              </p> 
     * <p>Create Time: 2011-5-10   </p> 
     * @author Semmy 
     * @param args 
     * @throws InterruptedException  
     */ 
    public static void main(String[] args) throws InterruptedException {  
        Test t=new Test();  
        Thread a=new Thread(new ThreadA(t));  
        a.start();  
        try {  
            Thread.sleep(2000);  
        } catch (InterruptedException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        t.methodB();  
    }  
 
}  
 
class ThreadA implements Runnable{  
    Test t;  
    public ThreadA(Test t) {  
        this.t=t;  
    }  
 
    public void run() {  
          
        try {  
            System.out.println("线程A执行,正在睡眠。。。。");  
            t.methodA("线程A调用");  
            System.out.println("线程A执行,完成睡眠。。。。");  
        } catch (InterruptedException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
    }  
      
}  
 
class Test{  
    private Integer x=new Integer(10);  
    public  void methodA(String str) throws InterruptedException {  
            synchronized(x){  
                System.out.println(str);  
                System.out.println("x在A中值为:"+x);  
                Thread.sleep(30000);  
                x-=1;  
                System.out.println("x在A中值为:"+x);  
            }  
    }  
    public void methodB() {
        synchronized(x){   //aaaaaa
        x-=1;  
        System.out.println("执行B方法");  
        System.out.println("x在B方法:"+x);  
        }
    }  

 

结果:

线程A执行,正在睡眠。。。。
线程A调用
x在A中值为:10
x在A中值为:9
线程A执行,完成睡眠。。。。
执行B方法
x在B方法:8

 

当 //aaaaaa注释,主线程调用methodB方法中对x对象操作不会被阻塞

 



 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值