通过验证,发现不是this,因为静态方法中也不可以定义this。
静态进内存时,内存中没有本类对象,但是一定有该类对应的字节码文件对象。
类名.class,该对象的类型是Class.
静态的同步方法,使用的锁是刚方法所在类的字节码文件对象,类名.class
class Ticket implements Runnable
{
private static int tick = 100;
Object obj = new Object();
public boolean flag=true;
public void run()
{
if (flag)
{
while (true)
{
//show();
synchronized(Ticket.class)
{
if(tick>0)
{
try {Thread.sleep(10);}catch (Exception e){}
System.out.println(Thread.currentThread().getName()+"code...sale:"+tick--);
}
}
}
}
else
while (true)
{
show();
}
}
public static synchronized void show()
{
if(tick>0)
{
try{Thread.sleep(10);}catch (Exception e){}
System.out.println(Thread.currentThread().getName()+"show...sale:"+tick--);
}
}
}
class StaticMethodDemo
{
public static void main(String[] args)
{
Ticket t = new Ticket();
new Thread(t).start();
try{Thread.sleep(10);}catch(Exception e){}
t.flag = false;
new Thread(t).start();
//new Thread(t).start();
//new Thread(t).start();
//new Thread(t).start();
}
}
同步函数用的是哪个锁呢?
函数需要被对象调用,那么函数都有一个所属对象引用。就是this。
所以同步函数使用的锁是this。
通过该程序进行验证。
使用两个线程来买票。
一个线程在同步代码块中。
一个线程在同步函数中。
都在执行卖票动作。
class Ticket implements Runnable
{
private int tick = 100;
Object obj = new Object();
public boolean flag=true;
public void run()
{
if (flag)
{
while (true)
{
//show();
synchronized(obj)
{
if(tick>0)
{
try {Thread.sleep(10);}catch (Exception e){}
System.out.println(Thread.currentThread().getName()+"code...sale:"+tick--);
}
}
}
}
else
while (true)
{
show();
}
}
synchronized void show()
{
if(tick>0)
{
try{Thread.sleep(10);}catch (Exception e){}
System.out.println(Thread.currentThread().getName()+"show...sale:"+tick--);
}
}
}
class ThisLockDemo
{
public static void main(String[] args)
{
Ticket t = new Ticket();
new Thread(t).start();
try{Thread.sleep(10);}catch(Exception e){}
t.flag = false;
new Thread(t).start();
//new Thread(t).start();
//new Thread(t).start();
//new Thread(t).start();
}
}