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终止,否则是没有办法输出完成的。求大神们帮忙解答!谢谢了!作者: zhouqun 时间: 2014-8-2 21:46
synchronized应该在while循环内,线程0进去之后一直有while循环,也补释放锁,别的线程也进不去啊,只能线程0一直执行作者: zhouqun 时间: 2014-8-2 21:47
class Sale implements Runnable { int tickets = 100; Object obj = new Object(); public void run() { while(true){ synchronized(obj){ 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(); } } 看下这个是否可以,作者: pig3156661 时间: 2014-8-3 09:18