对于这个问题,同步函数的锁是当前对象的锁,也就是this。
先看代码
补充:在静态函数里的同步代码块锁也是this
//静态同步函数进内存的时候不存在对象,但是存在其所属类的字节码文件对象,属于Class类型的对象,所以
//静态同步函数的锁是其所属类的字节码文件对象
class Ticket implements Runnable
{
private static int num = 50;
private Object obj = new Object();
boolean flag = true;
public void run()
{
if(flag)
{
while(true)
{
//如果这里是obj锁,那么两个同步块和函数是用的不同的锁,会产生错票。而当我们变为ticket.class锁后,那么就会完成同步
synchronized(obj)
{
if(num>0)
{
try{Thread.sleep(20);}catch(InterruptedException e){e.printStackTrace();}
System.out.println(Thread.currentThread().getName()+"...sale..."+num--);//1
}
}
fun();
}
}
else
while(true)
fun();
}
public static synchronized void fun()//Ticket.class //同步函数的锁是静态锁
{
if(num>0)
{
try{Thread.sleep(20);}catch(InterruptedException e){e.printStackTrace();}
System.out.println(Thread.currentThread().getName()+"...sale..."+num--);//1
}
}
}
class Demo6
{
public static void main(String[] args)
{
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
//让主线程放弃cpu
//若是没有这个让主线程让出cpu,那么会先让flag置为false,也就是两个线程都是进入的同步代码块。
//我们要两个不同的线程分别进入同步代码块和同步函数。
try{Thread.sleep(20);}catch(InterruptedException e){e.printStackTrace();}
// t.flag = false;
t2.start();
}
}