class Sale implements Runnable
{
int tickets = 100;
Object obj = new Object();
public void run()
{
synchronized(obj)
{
while(true)
{
try{Thread.sleep(10);}catch (Exception e){}
if (tickets>0)
System.out.println(Thread.currentThread().getName()+"…………"+tickets--);
}
}
}
}
class SaleTickets
{
public static void main(String[] args)
{
Sale s = new Sale();
Thread t1 = new Thread(s);
Thread t2 = new Thread(s);
Thread t3 = new Thread(s);
Thread t4 = new Thread(s);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
这个程序我用CMD输出后,放上同步代码块就只有0线程运行,而且CMD中就出现异常了,除非用CTRL+C终止,否则是没有办法输出完成的。求大神们帮忙解答!谢谢了! |
|