第九周课程总结&实验报告(七

 提交作业

实验任务详情:
完成火车站售票程序的模拟。
要求:
(1)总票数1000张;
(2)10个窗口同时开始卖票;
(3)卖票过程延时1秒钟;
(4)不能出现一票多卖或卖出负数号票的情况。

package 测试;

public class 火车站系统 {
	public static void main(String[] agrs) {
		MyThread mt =new MyThread();
		Thread t1 =new Thread(mt,"一号窗口");
		Thread t2 =new Thread(mt,"二号窗口");
		Thread t3 =new Thread(mt,"三号窗口");
		Thread t4 =new Thread(mt,"四号窗口");
		Thread t5 =new Thread(mt,"五号窗口");
		Thread t6 =new Thread(mt,"六号窗口");
		Thread t7 =new Thread(mt,"七号窗口");
		Thread t8 =new Thread(mt,"八号窗口");
		Thread t9 =new Thread(mt,"九号窗口");
		Thread t10 =new Thread(mt,"十号窗口");
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		t5.start();
		t6.start();
		t7.start();
		t8.start();
		t9.start();
		t10.start();
	}
}
class MyThread implements Runnable{
	private int ticket = 1000;
	public void run() {
		for(int i=0;i<1000;i++) {
			this.sale();
		}
	} 
	public synchronized void sale() {
		if(ticket>0){
			try {
				Thread.sleep(300);
			}catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName()+"卖票:剩下="+ticket--);
		}
	}
}


总结:Thread是一个线程操作类,可以产生许多的线程,并且可以同时工作。

posted on 2019-10-25 16:11  贺智超  阅读(109)  评论(0编辑  收藏  举报

导航