/*
java线程死锁的模拟
两个线程同时请求对方的对方释放监视对象 造成死锁
请在 虚拟机 单核下运行
*/
class Test
{
public static void main(String []args) throws Exception
{
ThreadOne td=new ThreadOne();
new Thread(td).start();
Thread.sleep(3);
new Thread(td).start();
}
}
class ThreadOne implements Runnable
{
int tickets=100;
Object obj=new Object();
boolean b=false;
public void run()
{
if(b==false)
{
while(true)
sell();
}
else
{
while(true)
{
synchronized(obj)
{
try
{
Thread.sleep(10);
}
catch(Exception e)
{
e.printStackTrace();
}
synchronized(this)
{
if(tickets>0)
{
System.out.println("obj:"+Thread.currentThread().getName()+
" sell tickets:"+tickets);
tickets--;
}
}
}
}
}
}
public synchronized void sell()
{
synchronized(obj)
{
if(tickets>0)
{
try
{
Thread.sleep(10);
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("sell():"+Thread.currentThread().getName()+
" sell tickets:"+tickets);
tickets--;
}
}
}
}