//方法1:不适用
/*
class Ticket extends Thread
{
private static int tick=100;//必须定义静态,不然每个线程都有100张票
public void run()
{
while(true)
{
if(tick>0)
{
System.out.println(this.getName()+"....sale:"+tick--);
}
}
}
}
public class ThreadDemo2
{
public static void main(String[] args)
{
Ticket t1 = new Ticket();
Ticket t2 = new Ticket();
Ticket t3 = new Ticket();
Ticket t4 = new Ticket();
t1.start();
t2.start();
t3.start();
t4.start();
}
}
*/
class Ticket implements Runnable
{
private int tick=TicketSealCenter.num;
Object obj = new Object();
public void run()
{
while(true)
{
synchronized(obj)
{
if(tick>0)
{
String name = Thread.currentThread().getName();
int windows = Integer.parseInt(name.substring(7, name.length()));
try{Thread.sleep(100);}catch(Exception e){}
System.out.println("第"+(windows+1)+"窗口卖出了第"+tick--+"张票");
}
}
}
}
}
//售票窗口通过for循环控制窗口数量
class SealWindow
{
public static void addWindow()
{
Ticket t = new Ticket();
for(int x=1;x<=4;x++)
{
Thread t1 = new Thread(t);
t1.start();
}
}
}
//售票中心控制票数
class TicketSealCenter
{
public static int num=100;
}
public class ThreadDemo2
{
public static void main(String[] args)
{
SealWindow.addWindow();
}
}