第九周作业

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

1)实验代码

package text8;

public class MyThread implements Runnable{

    private int tickets=1000;
    
    public int getTickets() {
        return tickets;
    }

    public void setTickets(int tickets) {
        this.tickets = tickets;
    }

    public void run() {
        while(true) {
            synchronized(this){
                try {
                    if(tickets>0) {
                        System.out.println(Thread.currentThread().getName()+":是第 "+tickets+" 张票 ");
                        tickets--;
                    }
                    Thread.sleep(1000);
                }catch(Exception e) {
                    System.out.println(e.getMessage());
                }
            }
            if(tickets<=0){
                break;
            }
        }
    }

}
package text8;

public class Text8 {

    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();
        
    }

}

2)运行截图

程总结
这周主要学习了多线程还学了一点关于Java的输入输出(主要是关于文件的)

多线程
Java中多线程的实现主要是通过继承Thread类或实现Runnable接口。其中Runnable接口可以资源共享。但不管使用哪种方法都要通过覆写run();

原文地址:https://www.cnblogs.com/zuoshuai/p/11740371.html