java模拟线程死锁
/*java线程死锁的模拟两个线程同时请求对方的对方释放监视对象 造成死锁请在 虚拟机 单核下运行*/class Test { public static void main(String []args) throws Exception
/*
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--;
}
}
}
}
更多推荐
所有评论(0)