多线程 - 窗口买票机制

public class Test extends Thread {
//通过构造方法给线程名字赋值
public Test(String name) {
super(name);
}
//保证持票数一致,票数要静态
static int tick = 2000;
//创建一个静态钥匙
static Object object = "这个有神用";

//重写run方法,实现买票操作
@Override
public void run() {
while (tick > 0) {
synchronized (object) {
if (tick > 0) {
System.out.println(getName() + "卖出了" + tick + "张票");
tick--;
} else {
System.out.println(getName() +"票卖完了");
}
}
try {
sleep(100);//休息一秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
/**
* 测试类
* @param args
*/
public static void main(String[] args) {
//实例化站台对象,并为每一个站台取名字
Test station1=new Test("窗口1");
Test station2=new Test("窗口2");
Test station3=new Test("窗口3");
Test station4=new Test("窗口4");
// 让每一个站台对象各自开始工作
station1.start();
station2.start();
station3.start();
station4.start();
}

猜你喜欢

转载自www.cnblogs.com/m-jj/p/11872201.html
今日推荐