JAVA中有许多方法可以实现多线程,本例中笔者想通过一个具体的例程来分享完善本专栏第10篇文章中所提到的通过继承Tread类来实现多线程的方法.
文章目录
题目重述
模拟航班售票系统,实现三个售票窗口发售某次航班的10张机票,一个售票窗口用一个线程来表示。
问题分析以及求解思路
待完善(请耐心等待)
程序代码
class Windows extends Thread
{
public static int num=10;
public static int flag=0;
public void run( )
{
synchronized(""){
while(true)
{
if(num>0)
{
try{Thread.sleep((int)(1000*Math.random()));}
catch(Exception e){e.printStackTrace();}
System.out.println(this.getName()+"窗口卖出一张票!余票数量为 : " + --num);
//if(flag==0){flag=1;break;}
// else if (flag==1){flag=0;break;}
}
else break;
}}
}
}
public class SellTickets
{
public static void main(String[ ] args)
{
int a=0,b=0,c=0;
while((a+b+c)!=10)
{
a=(int)(5*(Math.random()+1))%8;
b=8-a;
c=10-a-b;
}
System.out.println(a+b+c);
Windows c1 = new Windows( );
c1.start( );
Windows c2 = new Windows( );
c2.start( );
Windows c3 = new Windows( );
c3.start( );
}
}