public class Yugi implements Runnable
{
@Override
public void run()
{
String name = Thread.currentThread().getName();
while(name.startsWith("窗口"))
{
if(tickets.length == 0)
{
stop();
break;
}
int num = (int) (Math.random() * tickets.length) + 1;
tickets = new int[tickets.length - num];
System.out.println(name + " 售出了 " + num + " 张票");
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{}
}
}
public synchronized void start()
{
for(int i = 0; i < ts.length; i++)
{
Thread thread = ts[i];
if(thread == null)
{
thread = new Thread(this);
thread.setPriority(Thread.MIN_PRIORITY);
thread.setName("窗口" + (i + 1));
thread.start();
}
}
}
public synchronized void stop()
{
for(int i = 0; i < ts.length; i++)
{
Thread thread = ts[i];
if(thread != null)
{
thread.interrupt();
}
thread = null;
}
notifyAll();
}
static int[] tickets = new int[100];
private static int WIN = 5;
Thread[] ts = new Thread[WIN];
public static void main(String[] args)
{
new Yugi().start();
}
}