package cn.itcast01;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
*
* 3个窗口售100张票;
*
*/
public class Test4
{
public static void main(String[] args)
{
Selltickets s1 = new Selltickets();
Selltickets s2 = new Selltickets();
Selltickets s3 = new Selltickets();
s1.setName("窗口1");
s2.setName("窗口2");
s3.setName("窗口3");
s1.start();
s2.start();
s3.start();
}
}
class Selltickets extends Thread
{
public static int tickets=100;
//创建锁对象
public static Lock lock=new ReentrantLock();
public void run()
{
while(true)
{
lock.lock();
if(tickets>0)
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(getName()+"出售第"+tickets--+"张票");
}
lock.unlock();
}
}
}
|
|