class SellThread implements Runnable
{
int tickets=100;
Object obj=new Object();
boolean bl=true;
public void run()
{
if(bl==true)
{
while(true)
{
sell();
}
}
else
{
while(true)
{
synchronized(obj)
{
try
{
Thread.sleep(10);
}
catch (Exception e)
{
e.toString();
}
synchronized(this)
{
if(tickets>0)
{
System.out.println("Obj "+Thread.currentThread().getName()+
"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()+
"Tickets:"+tickets);
tickets--;
}
}
}
}
class TicketSystem
{
public static void main(String[] args)
{
SellThread st=new SellThread();
new Thread(st).start();//执行同步方法sell()
try
{
Thread.sleep(10);
}
catch (Exception e)
{
e.printStackTrace();
}
st.bl=false;
new Thread(st).start();
}
}
为什么结果如下呢?
sell<>Thread-0Tickets:100
sell<>Thread-0Tickets:99
sell<>Thread-0Tickets:98
sell<>Thread-0Tickets:97
sell<>Thread-0Tickets:96
{
int tickets=100;
Object obj=new Object();
boolean bl=true;
public void run()
{
if(bl==true)
{
while(true)
{
sell();
}
}
else
{
while(true)
{
synchronized(obj)
{
try
{
Thread.sleep(10);
}
catch (Exception e)
{
e.toString();
}
synchronized(this)
{
if(tickets>0)
{
System.out.println("Obj "+Thread.currentThread().getName()+
"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()+
"Tickets:"+tickets);
tickets--;
}
}
}
}
class TicketSystem
{
public static void main(String[] args)
{
SellThread st=new SellThread();
new Thread(st).start();//执行同步方法sell()
try
{
Thread.sleep(10);
}
catch (Exception e)
{
e.printStackTrace();
}
st.bl=false;
new Thread(st).start();
}
}
为什么结果如下呢?
sell<>Thread-0Tickets:100
sell<>Thread-0Tickets:99
sell<>Thread-0Tickets:98
sell<>Thread-0Tickets:97
sell<>Thread-0Tickets:96
楼主【fwloveyou】截止到2008-08-02 17:19:19的历史汇总数据(不包括此帖):
发帖的总数量:19 发帖的总分数:170 每贴平均分数:8
回帖的总数量:6 得分贴总数量:0 回帖的得分率:0%
结贴的总数量:18 结贴的总分数:110
无满意结贴数:15 无满意结贴分:410
未结的帖子数:1 未结的总分数:60
结贴的百分比:94.74 % 结分的百分比:64.71 %
无满意结贴率:83.33 % 无满意结分率:372.73%
值得尊敬
取消马甲机器人,请点这里:http://www.java2000.net/mycsdn/robotStop.jsp?usern=fwloveyou