zoukankan      html  css  js  c++  java
  • 第九周课程总结&实验报告(七)

    实验报告

    实验任务详情:

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

    一:实验代码

    package 第九周课程总结;
    class test implements Runnable {
        static int ticket = 999;
        public void run() {
           for (int i = 0; i < 1000; i++)
             synchronized (this) {
                 if (ticket >= 0) {
                     if (ticket == 0) {
                       System.out.println(Thread.currentThread().getName() + "票已售罄");
                         break;} 
                         else {
                    try {
                        Thread.sleep(1000);
                         } 
                    catch (InterruptedException e) {
                        e.printStackTrace();
                          }
                    System.out.println(Thread.currentThread().getName() + "卖出一张票" + " " + "所剩余票为:" + ticket);
                         ticket--;
                     }
                 }
             }
        }
    }
    
    public class ticket {
        public static void main(String args[]) {
            test t = new test();
            Thread th1 = new Thread(t, "窗口一");
            Thread th2 = new Thread(t, "窗口二");
            Thread th3 = new Thread(t, "窗口三");
            Thread th4 = new Thread(t, "窗口四");
            Thread th5 = new Thread(t, "窗口五");
            Thread th6 = new Thread(t, "窗口六");
            Thread th7 = new Thread(t, "窗口七");
            Thread th8 = new Thread(t, "窗口八");
            Thread th9 = new Thread(t, "窗口九");
            Thread th10 = new Thread(t, "窗口十");
    
            th1.start();
            th2.start();
            th3.start();
            th4.start();
            th5.start();
            th6.start();
            th7.start();
            th8.start();
            th9.start();
            th10.start();
        }
    }

    二:运行截图

     

     

     

     实验总结:写这实验的时候,遇到了一张票被多次销售的问题,或者只出售一个窗口,然后通过咨询同学发现要使用同步代码块,然后问题就解决了.

  • 相关阅读:
    《构建之法》阅读报告
    教务管理系统类图及数据库E/R图
    设计模式:抽象工厂
    结对项目:四则运算程序测试
    Leetcode笔记之57和为s的连续正数序列
    Leetcode笔记之1103分糖果 II
    Leetcode笔记之199二叉树的右视图
    每日Scrum(9)
    每日Scrum(7)
    每日Scrum(6)
  • 原文地址:https://www.cnblogs.com/duweihhw/p/11737360.html
Copyright © 2011-2022 走看看