上面的回答 太复杂了,既然要同步,那么放一个本类对象就可以 本类对象不用重新创建 用this就可以了 你们忘了么?
class Ticket implements Runnable
{
private static Integer ticket = 50;
public void run()
{
while(true)
{
synchronized(this)//这不就搞定了么??
{
if (ticket >= 1)
{
try { Thread.sleep(100);}catch (Exception e) { }
System.out.println(Thread.currentThread().getName() + " Ticket " + ticket + " is solt");
--ticket;
}
else
{
return;
}
}
}
}
}
public class TicketDemo
{
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();
}
} |