在上一篇文章中写到了许多线程共享同一数据,这种情况在现实的生活中也是经常发生的,比如火车站的火车票售票系统。火车票售票系统是一个常年运行的系统,为了满足乘客的需求,我们不能只设一个窗口,必须设很多的售票窗口,每个售票窗口就像一个线程,它们各自运行,共同访问相同的数据——火车票的数量,下面我们用多线程模仿一下火车票售票系统:
public
class TicketSystem
{
public static void main(String[] args)
{
SellThread st=new SellThread();
new Thread(st).start();new Thread(st).start();new Thread(st).start();
}
}
class
SellThread implements Runnable{
int tickets=100;
public void run()
{
while(true)
{
if(tickets>0)
{
System.out.println("obj: