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

                                               实验报告(七)

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

实验代码:

package Wdnmd;

 class MyThread implements Runnable{
    private int ticket=100;
    
    private boolean flag=true;
    public void run() {
        while(flag) {
             try {
                 Thread.sleep(50);
             }catch(Exception e) {
                 e.printStackTrace();
             }
            sale();
            if(flag==false) {
                System.out.println(Thread.currentThread().getName()+"窗口票已全部卖完");
            }
         }
         
    }
    public synchronized void sale() {
         if(ticket==0) {
             flag=false;
              return;
         }
        
         System.out.println(Thread.currentThread().getName()+"窗口卖票一张,余票为"+ticket--);
   }
     
 }
public class ThreadNameDemo {
     public static void main(String args[]) {
         MyThread m=new MyThread();
         for(int i=1;i<=10;i++) {
         new Thread(m,i+"窗口").start();
         }
     }
         
    
}

运行截图:

 

                                               第九周课程总结

本周学习了多线程
线程操作我们可以通过Thread类和Runnable类来实现
Thread类实现了Runnable接口,在Thread类中,有一些比较关键的属性,比如name是表示Thread的名字,必须依靠Thread才能启动多线程。
可以通过Thread类的构造器中的参数来指定线程名字,priority表示线程的优先级,daemon表示线程是否是守护线程,target表示要执行的任务。
Thread类中常用的方法:
关系到线程运行状态的方法:start方法:start()用于启动一个线程,当调用start方法后,系统会开启一个新的线程来执行用户定义的子任务,这个过程中,会为相应的线程分配需要的资源。
run方法:run()方法是不需要用户来调用的,当通过start方法启动一个线程之后,当线程获得了CPU执行时间,便进入run方法体去执行具体的任务。
继承Thread类必须重写run方法,在run方法中定义具体要执行的任务。
sleep方法:Thread类在java.lang包中定义的。一个类只要继承了Thread类同时覆写了本类中的run()方法就可以实现多线程操作了,但一个类只能继承一个父类。
在使用Runnable定义的子类中没有start()方法,只有Thread类中才有。
线程的操作的相关方法见P257 表9-2
还学习了File类
File 类是 java.io 包中唯一代表磁盘文件本身的对象。File 类定义与平台无关的方法来操作文件,File类主要用来获取或处理与磁盘文件相关的信息如文件名、 文件路径、访问权限和修改日期等,
还可以浏览子目录层次结构。
File类构造方法:
File(File parent,String child):根据 parent 抽象路径名和 child 路径名字符串创建一个新 File 实例。
File(String pathname):通过将给定路径名字符串转换成抽象路径名来创建一个新 File 实例。如果给定字符串是空字符串,则结果是空的抽象路径名。
File(String parent,String child):根据 parent 路径名字符串和 child 路径名字符串创建一个新 File 实例。
File类主要方法和常量见P370 表12-1
原文地址:https://www.cnblogs.com/wangdian1/p/11739770.html