完成火车站售票程序的模拟。
要求:
(1) 总票数1000张;
(2) 10个窗口同时开始卖票;
(3) 卖票过程延时1秒钟;
(4)不能出现一票多卖或卖出负数号票的情况。
实验代码:
package com.cissst.software.synthread;
public class MainThread {
public static void main(String[] args) {
MyThread sicket=new MyThread();
Thread t1 = new Thread(sicket,"窗口一");
Thread t2 = new Thread(sicket,"窗口二");
Thread t3 = new Thread(sicket,"窗口三");
Thread t4 = new Thread(sicket,"窗口四");
Thread t5 = new Thread(sicket,"窗口五");
Thread t6 = new Thread(sicket,"窗口六");
Thread t7= new Thread(sicket,"窗口七");
Thread t8 = new Thread(sicket,"窗口八");
Thread t9 = new Thread(sicket,"窗口九");
Thread t10 = new Thread(sicket,"窗口十");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
t8.start();
t9.start();
t10.start();
}
}
package com.cissst.software.synthread;
class MyThread implements Runnable {
private int count = 1000;
Object lock = new Object();
@Override
public void run() {
while(count > 0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(lock){
if(count > 0){
System.out.println(Thread.currentThread().getName()+"正在售第" + count + "张车票"); //售完一张车票,剩余总票数减一
count --;
}
}
}
}
}
实验结果: