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

实验任务详情:

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

源代码:

package 实验七;

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

public class Test {

    public static void main(String[] args) {
        MyThread mt=new MyThread();
        
        new Thread(mt,"窗口1:").start();
        new Thread(mt,"窗口2:").start();
        new Thread(mt,"窗口3:").start();
        new Thread(mt,"窗口4:").start();
        new Thread(mt,"窗口5:").start();
        new Thread(mt,"窗口6:").start();
        new Thread(mt,"窗口7:").start();
        new Thread(mt,"窗口8:").start();
        new Thread(mt,"窗口9:").start();
        new Thread(mt,"窗口10:").start();
    }

}

运行截图

 总结:此题包含线程的休眠,线程同步等,上课老师也讲过,就是题目要求第二点要求10个窗口同时售票,所以要吧同步代码块放在try后面。

学习总结

线程的操作方法    

构造:1、Runnable target (接受Runnable接口子类对象,实例化Thread对象)

     2、String name 实例化Thread对象并设置线程名称。

普通:1、currentThread()返回目前正在执行的线程

     2、getName()返回线程的名称

     3、getPriority()发挥线程的优先级

     4、isInterrupted()判断线程是否在活动,如果,返回true;否则,返回false

     5、run()执行线程

     6、start()开始执行线程。

     7、Thread.sleep()线程的休眠

以上列出线程操作方法的一些重要方法。

File类的基本介绍

File类的构造方法:

public File(String pathname)->实例化File的时候,必须设置好路径
原文地址:https://www.cnblogs.com/JokerXue/p/11737991.html