本帖最后由 魏亮 于 2012-9-14 10:54 编辑
/*
死锁。
同步中嵌套同步。
*/
package cn.itcast.thread;
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(5);
}
catch (Exception e)
{
}
t2.start();
}
}
class Ticket implements Runnable
{
int ticket=100;
boolean flag=true;
Object obj = new Object();
public void run()
{
if (flag)
{
while(true)
{
synchronized(obj)
{
try
{
Thread.sleep(5);
}
catch (Exception e)
{
}
show();
//if(ticket>0)
// System.out.println(Thread.currentThread().getName()+"::"+ticket--);
}
}
}
else
while(true)
show();
}
public synchronized void show()
{
synchronized(obj)
{
if(ticket>0)
{
System.out.println(Thread.currentThread().getName()+"::"+ticket--);
}
}
}
}
编译时的错误报告是 错误: 进行语法分析时已到达文件结尾
自己找了半天没找出来,请大家帮忙看看
|
|