编辑器: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();
}
}