多线程---静态同步函数的锁是class(转载)

/**
如果同步函数被静态修饰,那么他的锁就是该方法所在类的字节码文件对象 类名.class
静态进内存时,内存中没有本类对象,但是一定有该类对应的字节码文件对象。
该对象就是:类名.class   该对象的类型是class
**/
class Ticket implements Runnable
{
private static int tick = 100;
Object obj = new Object();
boolean flag = true;
public void run()
{
if(flag)
{
while(true)
synchronized(Ticket.class)//注意这里的锁要一致
 //跟show()函数一样都是一个锁,show()锁是本身所以是this
 //同步的前提是:1、两个及其以上的线程;2、锁一样
{
if(tick>0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"同步代码块"+tick--);
}
}
}else
{
while(true)
show();
}
}
public static synchronized void show()//锁是this
{
if(tick>0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"同步函数...."+tick--);
}
}
}
class ThisLock
{
public static void main(String[] args)
{
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
try{Thread.sleep(10);}catch(Exception e){}
t.flag = false;
t2.start();
}
}
原文地址:https://www.cnblogs.com/kevinfuture/p/4283939.html