第九周课程总结&实验报告(七)
完成火车站售票程序的模拟。
要求:
(1)总票数1000张;
(2)10个窗口同时开始卖票;
(3)卖票过程延时1秒钟;
(4)不能出现一票多卖或卖出负数号票的情况。
实验代码
package t; class MyThread implements Runnable{ private int ticket = 1 ; public void run(){ for(int i=0;i<1000;i++){ synchronized(this){ if(ticket<=1000){ try{ Thread.sleep(1000) ; }catch(InterruptedException e){ e.printStackTrace() ; } System.out.println(Thread.currentThread().getName()+"卖票:ticket = " + ticket++ ); } } } } } public class h{ public static void main(String args[]){ MyThread my = new MyThread(); Thread d1 = new Thread(my,"窗口1"); Thread d2 = new Thread(my,"窗口2"); Thread d3 = new Thread(my,"窗口3"); Thread d4 = new Thread(my,"窗口4"); Thread d5 = new Thread(my,"窗口5"); Thread d6 = new Thread(my,"窗口6"); Thread d7 = new Thread(my,"窗口7"); Thread d8 = new Thread(my,"窗口8"); Thread d9 = new Thread(my,"窗口9"); Thread d10 = new Thread(my,"窗口10"); d4.setPriority(Thread.MIN_PRIORITY) ; d5.setPriority(Thread.MAX_PRIORITY) ; d6.setPriority(Thread.NORM_PRIORITY) ; d1.start() ; d2.start() ; d3.start() ; d4.start() ; d5.start() ; d6.start() ; d7.start() ; d8.start() ; d9.start() ; d10.start() ; } }
结果截图
![](https://img2018.cnblogs.com/blog/1581756/201910/1581756-20191025125005653-1197595596.png)
本周总结:
1.线程操作的主要方法
2.在Thread类中,可以通过getName()方法取得线程的名称,通过setName()方法设置线程的名称。
3.在线程强制运行期间,其他线程无法运行,必须等待此线程完成之后才可以继续执行。