基于synchronized的对象锁,类锁以及死锁模拟

本文通过实例详细讲解了Java中的synchronized关键字使用,包括对象锁、类锁的实现,并通过代码展示了死锁的情况。在对象锁中,不同对象访问不会相互阻塞;类锁则确保同一时刻只有一个线程访问,不同对象访问类锁会产生阻塞。同时,文章通过E和E1类的静态同步方法模拟了死锁,两个线程各自持有对方需要的锁,导致双方都无法继续执行。
摘要由CSDN通过智能技术生成
分为对象锁和类锁
public class T {

	public void test1() throws Exception{
     synchronized(this){ //对象锁
    	 System.out.println(Thread.currentThread().getName()+"---test1  Doing");
    	 Thread.currentThread().sleep(2000);
    	 test2();
     };
	}
	
	public synchronized void test2() throws Exception{ //同test1方法
	    System.out.println(Thread.currentThread().getName()+"--- test2 Doing");
	    Thread.currentThread().sleep(2000);
	    test1();
	}
	
	public void testclass1() throws Exception{
	     synchronized(T.class){//类锁
	    	 System.out.println(Thread.currentThread().getName()+"---testclass1  Doing");
	    	 Thread.currentThread().sleep(2000);
	    	 
	     };
	}
	
	public static synchronized void testclass2() throws Exception{ //同testclass1方法
    	 System.out.println(Thread.currentThread().getName()+"---testclass2  Doing");
    	 Thread.currentThread().sleep(2000);
    	 testclass3();
	}
	
	public static synchronized void testclass3() throws Exception{ //同testclass1方法
   	  System.out.println(Thread.currentThread().getName()+"---testclass3  Doing");
   	  Thread.currentThread().sleep(2000);
   	  testclass2();
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值