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

    Java实验报告

    实验任务详情:

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

    实验源码:
    public class Pluto {
    
        public static void main(String[] args) {
            SafeWeb web=new SafeWeb();
            new Thread(web,"窗口1").start();
            new Thread(web,"窗口2").start();
            new Thread(web,"窗口3").start();
            new Thread(web,"窗口4").start();
            new Thread(web,"窗口5").start();
            new Thread(web,"窗口6").start();
            new Thread(web,"窗口7").start();
            new Thread(web,"窗口8").start();
            new Thread(web,"窗口9").start();
            new Thread(web,"窗口10").start();
        }
    
    }
    class SafeWeb implements Runnable{
        private int ticket=1000;
        private boolean flag=true;
        public void run() {
            while(flag) {
                try {
                    Thread.sleep(1000);
                }catch(Exception e) {
                    e.printStackTrace();
                }
                test();
            }
        }
        public synchronized void test() {
            if(ticket<0) {
                flag=false;
                return;
            }
            try {
                Thread.sleep(1000);
            }catch(Exception e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"售出一张,:总剩余:"+ticket--);
        }
    }
     
     
    实验结果:
     
    实验总结:
    本周作业由于经过讲解,以及书上有关知识综合,使得题目理解更加清晰明朗了。
    这一周我们学习了

    Thread类继承
    一个类只要继承了Thread类,就称为多线程操作,在Thread子类中,必须明确覆写run()方法;启动线程用start()方法。

    Runnable接口
    因为启动一个多线程必须要使用start()方法,所以本质还是依靠Thread类启动。
    Runnable接口可以资源共享;
    同步与死锁:如果多个线程需要操作,统一资源时就有可能出现资源的同步问题。 

     
  • 相关阅读:
    P4005 小 Y 和地铁
    P1039 侦探推理
    P2766 最长不下降子序列问题
    P2312 解方程
    P2169 正则表达式
    UOJ#22. 【UR #1】外星人
    UOJ#21. 【UR #1】缩进优化
    Palindromeness CodeChef
    bzoj5392 [Lydsy1806月赛]路径统计
    997D Cycles in product
  • 原文地址:https://www.cnblogs.com/ck11-06/p/11740977.html
Copyright © 2011-2022 走看看