学习到多线程和同步问题,写了个简单的卖票程序。希望能实现如下要求:
1.用4台售票机(4个线程)进行售票;
2.总共有100张票,票售完后,希望程序能终止运行。但是下面的代码只能保证同步,但是售票完毕后各个售票机还在不停运行(程序没有停下来),不知道有什么比较好的解决方法没。Java语言: 售票程序
public class SaleTickets
{
public static void main(String[] args)
{
TestSaleTickets tst=new TestSaleTickets();
new Thread(tst).start();
new Thread(tst).start();
new Thread(tst).start();
new Thread(tst).start();
}
}class TestSaleTickets implements Runnable
{
public static int num=100;
public void run()
{
while(true)
{
synchronized(this)
{
if(num>0)
{
System.out.println(Thread.currentThread().getName()+“卖出第”+num+“张火车票….”);
num–;
}
}
}
} }
if(num>0)
{
System.out.println(Thread.currentThread().getName()+“卖出第”+num+“张火车票….”);
num–;
}else{
break;
}