public class TicketSystem { public static void main(String a[]) { SellThread st=new SellThread(); new Thread(st).start(); new Thread(st).start(); new Thread(st).start(); new Thread(st).start(); }} class SellThread implements Runnable { private int tickets=100; private Object o = new Object(); public void run() { // 加锁同步操作 synchronized (o) { while(tickets>0) { System.out.println(Thread.currentThread().getName()+" sell tickets:"+tickets); tickets--; } // Initialize the tickets,如果想看到所有线程执行的效果,请加上这一句,否则的话请注掉 if (tickets==0) tickets = 100; } } } 线程执行无先后顺序,所以你每次运行的结果可能会不同。
{
public static void main(String a[])
{
SellThread st=new SellThread();
new Thread(st).start();
new Thread(st).start();
new Thread(st).start();
new Thread(st).start();
}}
class SellThread implements Runnable
{
private int tickets=100;
private Object o = new Object();
public void run()
{
// 加锁同步操作
synchronized (o)
{
while(tickets>0)
{
System.out.println(Thread.currentThread().getName()+" sell tickets:"+tickets);
tickets--;
}
// Initialize the tickets,如果想看到所有线程执行的效果,请加上这一句,否则的话请注掉
if (tickets==0) tickets = 100;
}
}
} 线程执行无先后顺序,所以你每次运行的结果可能会不同。