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

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

实验代码

package 实验七;

public class MyThread  implements Runnable{
     private int ticket=1000;
     public void run() {
          for(int i=0;i<1000;i++) {
               synchronized(this) {
                  if(ticket>0) {
                      try {
                          Thread.sleep(1000);
                      }catch(Exception e) {
                          e.printStackTrace();
                      }
                      System.out.println(Thread.currentThread().getName()+"正在售票,ticket="+ticket--);
                 }
             }
         }
     }
}

测试类test

public class test {
    public static void main(String[] args) {
        MyThread mt=new MyThread();
        Thread t1=new Thread(mt,"窗口1");
        Thread t2=new Thread(mt,"窗口2");
        Thread t3=new Thread(mt,"窗口3");
        Thread t4=new Thread(mt,"窗口4");
        Thread t5=new Thread(mt,"窗口5");
        Thread t6=new Thread(mt,"窗口6");
        Thread t7=new Thread(mt,"窗口7");
        Thread t8=new Thread(mt,"窗口8");
        Thread t9=new Thread(mt,"窗口9");
        Thread t10=new Thread(mt,"窗口10");          
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
        t7.start();
        t8.start();
        t9.start();
        t10.start();
    }
}

实验结果


本周总结

  • 学习了Thread和Runnable接口
  • 多线程的学习与应用
  • 学习JAVA最重要的就是上完课自己回寝室自己看书加以理解,这样能够深入的理解JAVA这门语言,好好加油!

版权声明:本文为LuZhenYu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/LuZhenYu/p/11740857.html