lock 的易错点

如果按下面的方式写lock,你会发现lock并没有起到作用。

 public static class count{
	  // private int i ;
	   public  void get(){
		   final ReentrantLock lock = new ReentrantLock();                             //lock 声明在函数内
		   try{
			   lock.lock();
			   System.out.println(Thread.currentThread().getName()+"   get begin");
			   Thread.sleep(100);
			   System.out.println(Thread.currentThread().getName()+"   get end");
			   lock.unlock();
		   }catch(InterruptedException e){
			   e.printStackTrace(); 
		   } 
		   
	   }
	   public  void put(){
		   final ReentrantLock lock = new ReentrantLock();                             //lock 声明在函数内
		   try{
			   lock.lock();
			   System.out.println(Thread.currentThread().getName()+"   put begin");
			   Thread.sleep(100);
			   System.out.println(Thread.currentThread().getName()+"   put end");
			   lock.unlock();
		   }catch(InterruptedException e){
			   e.printStackTrace(); 
		   } 
		   
	   }
   }

结果如下:

Thread-0   put begin
Thread-1   put begin
Thread-2   get begin
Thread-3   get begin
Thread-3   get end
Thread-0   put end
Thread-1   put end
Thread-2   get end

原因在于lock的声明在函数内,线程调用函数得到的lock值互不影响,所有并没有实现互斥。

改为如下:


public static class count{
		    final ReentrantLock lock = new ReentrantLock();                                    //lock 声明在函数外
		   public void get(){
			   try{
				   lock.lock();
				   System.out.println(Thread.currentThread().getName()+"   get begin");
				   Thread.sleep(1000);
				   System.out.println(Thread.currentThread().getName()+"   get end");
				   lock.unlock();
			   }catch(InterruptedException e){
				   e.printStackTrace(); 
			   } 
			   
		   }
		   public void put(){
			   
			   try{
				   lock.lock();
				   System.out.println(Thread.currentThread().getName()+"   put begin");
				   Thread.sleep(1000);
				   System.out.println(Thread.currentThread().getName()+"   put end");
				   lock.unlock();
			   }catch(InterruptedException e){
				   e.printStackTrace(); 
			   } 
			   
		   }
	   }


结果如下:

Thread-0   get begin
Thread-0   get end
Thread-1   get begin
Thread-1   get end
Thread-2   put begin
Thread-2   put end
Thread-3   put begin
Thread-3   put end



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值