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

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

package work;

public class MyThread implements Runnable {    
    private int ticket = 1000;                           
    public void run() {                                       
        for (int i=0;i<2000;i++) {                       
            synchronized (this) {                     
                if (ticket>0) {                      
                    try {
                        Thread.sleep(1000);          
                    }catch (InterruptedException e) {            
                        e.printStackTrace();                 
                    }
                    System.out.println(Thread.currentThread().getName()+"售票:ticket = " + ticket--);             
                }
            }
        }
    }
 
 public static void main (String[] args) {
        MyThread mt = new MyThread();           
        Thread[] m=new Thread[10];                  
        for(int i=0;i<10;i++) {                          
            m[i]=new Thread(mt);
            m[i].setName("窗口"+i);                  
            m[i].start();                                  
        }
        
    
    }

}

总结:1)start方法:start()用来启动一个线程,当调用start方法后,系统才会开启一个新的线程来执行用户定义的子任务,在这个过程中,会为相应的线程分配需要的资源。
           2)run方法:run()方法是不需要用户来调用的,当通过start方法启动一个线程之后,当线程获得了CPU执行时间,便进入run方法体去执行具体的任务。注意,继承Thread类必须重写run方法,在run方法中定义具体要执行的任务。
           3):如果在一个类里面使用线程,必须扩展Thread类,使自己成为它的子类,线程的处理必须编写在run方法里面;
           4)interrupt()方法中断线程执行,join()方法强制执行自己,其他线程无法执行;
原文地址:https://www.cnblogs.com/FLZ1208/p/11738321.html