Locks In Synchronized Methods

Locks In Synchronized Methods

When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.

注意这句:it automatically acquires the intrinsic lock for that method's object and releases it when the method returns.他锁的是调用该方法的对象

在他锁对象而没有释放锁时,其他线如果要调用该对象的其他同步方法,需要等此方法释放锁后才能调用,

下面看一下例子:

public class Deadlock2 {
	 static class Friend {
	        private final String name;
	        public Friend(String name) {
	            this.name = name;
	        }
	        public String getName() {
	            return this.name;
	        }
	        public synchronized void bow() throws InterruptedException {
	        	
	            Thread.currentThread().sleep(500000);
	        }
	       public synchronized void hello(){
	    	   System.out.println("hello");
	       }
	    }

/*
 * 不同线程调用同一对象的synchronized方法,要等第一个方法alphonse.bow();释放锁后,才能调用alphonse.hello();
 */
	 public static void main(String[] args) {
	        final Friend alphonse =
	            new Friend("Alphonse");
	       
	        new Thread(new Runnable() {
	            public void run() { try {
					alphonse.bow();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} }
	        }).start();
	        new Thread(new Runnable() {
	            public void run() { 
					alphonse.hello();
				
				} 
	        }).start();
	      
	    }
	 /*
	  *  不同线程,调用同一类对象alphonseX,两个对象锁互不影响
	  */
	 /*public static void main(String[] args) {
	        final Friend alphonse =
	            new Friend("Alphonse");
	        final Friend alphonse2 =
		            new Friend("Alphonse2");
	        new Thread(new Runnable() {
	            public void run() { try {
					alphonse.bow();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} }
	        }).start();
	        new Thread(new Runnable() {
	            public void run() { 
					//alphonse.bow();
					alphonse2.hello();
				
				} 
	        }).start();
	      
	    }*/

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值