Java笔记十三 验证静态同步函数的锁

编辑器:Notepad++;学习视频:毕向东Java基础教程

/*
验证静态同步函数的锁:
    该函数所属的字节码文件对象,
	可以用this.getClass()获取,
	也可以用该函数所在的 类名.class获取
*/

 
 //第一步:实现Runnable接口
 class Ticket1 implements Runnable  //不使用继承,避免多个线程卖相同的票(可将num定义成静态的来解决)
{
	private static  int num = 100;  //卖100张票
	boolean flag = true;
	//Object obj = new Object();
	
	//第二步:覆盖run方法
	public void run()
   {
	   if(flag)
	   {
		   while(true)
		   {
			    //synchronized(obj)
				synchronized(this.getClass())   //synchronized(Ticket1.class) 
				{
					if(num>0)
					{
						try{Thread.sleep(14);}catch(InterruptedException e){} 
						System.out.println(Thread.currentThread().getName()+"...synCodeBlock...sale-"+num--);
					}
				
				}
			}
	   }
	   else
	   {
		   while(true)
		   {
			   this.show();  //同步函数的锁,this
		   }
	   }
   }
   
   public static synchronized void show()
   {
	   if(num>0)
	   {
			try{Thread.sleep(14);}catch(InterruptedException e){} 
			System.out.println(Thread.currentThread().getName()+"...synFunc...sale-"+num--);
	   }
   }
}

class StaticSynFunClock
{
	public static void main(String[] args)	
    {
		//第三步:实例化Runnable接口子类对象,并作为参数传递给Thread
		Ticket1 t = new Ticket1();  //只需要实例化一次ticket类,如果继承,需要几个线程,就得实例化几次,导致一张票卖多次的问题
		Thread t1 = new Thread(t);
		Thread t2 = new Thread(t);
		
		//第四步:调用start()方法,开启线程
		t1.start();
		try{Thread.sleep(14);}catch(InterruptedException e){}
		t.flag = false;		
		t2.start();
    } 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值