}
}
}
}
}
}
}
}编译运行:

要解决这个问题,要涉及到线程的同步问题。
■ 线程同步
同步的两种方式:同步块和同步方法。
上面程序中,if语句块是一个临界区,要实现线程互斥地访问共享变量tickets。
用同步块实现如下:

class TicketSystem...{
public static void main(String[] args)...{
SellThread st=new SellThread();
new Thread(st).start();
new Thread(st).start();
new Thread(st).start();
new Thread(st).start();
new Thread(st).start();
}
}
class SellThread implements Runnable...{
int tickets=20;
Object obj=new Object(); //定义一个对象
public void run()...