本帖最后由 yinbolove576 于 2013-4-22 12:47 编辑
class Ticket implements Runnable
{
private int tick = 100;
Object obj = new Object();
public void run()
{
while(true)
{
synchronized(obj)
{
if(tick>0)
{
try{Thread.sleep(10);}catch (Exception e){}
System.out.println(Thread.currentThread().getName()+"...sale: "+tick--);
}
}
}
}
}
class TicketDemo2
{
public static void main(String[] args)
{
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
求大神解释下,为何小弟在添加了同步代码块synchronized 后,运行的结果都是Thread-0的线程而没有出现其余线程,运行多次都是这个结果,跪求原因,谢谢!
|
-
1.jpg
(21.6 KB, 下载次数: 23)
|