方法锁、对象锁、类锁区别

方法锁:

方法锁是对象锁的一种:

代码:四个窗口售票。每个窗口卖4张,一个窗口卖完下一个在卖

/**
 * 对象锁,方发锁,类锁
 * 
 * @author my
 *
 */
public class ObjectLock {
	public synchronized void sellTickets() { //方发锁,对象锁的一种
		int n = 4;
		while(n>0) {
			System.out.println(Thread.currentThread().getName() + " 票数" + n);
			n--;
			
		}
		
	}

public static void main(String[] args) {
	ObjectLock ol = new ObjectLock();
	Thread t1 = new Thread(new Runnable() {

		@Override
		public void run() {
			ol.sellTickets();
			
		}
		
	});
	Thread t2  = new Thread(new Runnable() {

		@Override
		public void run() {
			ol.sellTickets();
			
		}
		
	});
	Thread t3 = new Thread(new Runnable() {

		@Override
		public void run() {
			ol.sellTickets();
			
		}
		
	});
	Thread t4  = new Thread(new Runnable() {

		@Override
		public void run() {
			ol.sellTickets();
			
		}
		
	});
	
	t1.start();
	t2.start();
	t3.start();
	t4.start();
}

}

对象锁

public  void sellTickets() { //public synchronized void sellTickets() 方法锁,对象锁的一种
		synchronized(this) { //synchronized(this) 对象锁,四个线程都是访问的同一个对象,所以锁得住
			int n = 4;
			while(n>0) {
				System.out.println(Thread.currentThread().getName() + " 票数" + n+" 当前对象锁this为:"+this);
				n--;
				
			}
		}
		
	}

不同对象进行测试:很明显,this是锁不住的

/*
	 * 不同的对象ol2,来测试对象锁
	 */
	ObjectLock ol2 = new ObjectLock();
	Thread different = new Thread(new Runnable() {

		@Override
		public void run() {
			ol2.sellTickets();
			
		}
		
	},"different object");
	different.start();

类锁:

不同对象一样锁住了
其实类锁只是一个概念上的东西,并不是真实存在的,它只是用来帮助我们理解锁定实例方法和静态方法的区别的

代码块方式:

public  void sellTickets() { 
	synchronized(ObjectLock.class) { //类锁,不同对象一样锁住了
		int n = 4;
		while(n>0) {
			System.out.println(Thread.currentThread().getName() + " 票数" + n+" 当前对象锁this为:"+this);
			n--;
			
		}
	}

修饰方法的方式

public static synchronized void add(int m){  
    String name = Thread.currentThread().getName();  

    System.out.println("类锁");   
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值