class Ticket implements Runnable
{
private int num=100;
Object obj=new Object();
boolean flag=true;
public void run()
{
if (flag)
{
while (true)
{
synchronized(obj)//同步代码块中的是同步函数
{
show();//它的锁其实是this
}
}
}
else
while(true)
this.show();
}
public synchronized void show()//同步函数中加入同步代码块且它的锁是obj
{
synchronized(obj)
{
if (num>0)
{
try{Thread.sleep(10);}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+"...sale..."+num--);
}
}
}
}
class DeadLockDemo
{
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(InterruptedException e){}
t.flag=false;
t2.start();
}
}
class DeadLockDemo
{
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(InterruptedException e){}
t.flag=false; //这个修改对线程内不同步,不生效。所以先锁obj,再锁show,不会出现死锁
t2.start();
}
}