第九周总结&实验报告七

完成火车站售票程序的模拟。

要求:
(1)总票数1000张;
(2)10个窗口同时开始卖票;
(3)卖票过程延时1秒钟;
(4)不能出现一票多卖或卖出负数号票的情况。
一:实验代码

package first;
class MyThread implements Runnable{
    private int ticket = 1 ;    
    public void run(){
        for(int i=0;i<1000;i++){
            synchronized(this){ 
                if(ticket<=1000){  
                    try{
                        Thread.sleep(1000) ;    
                    }catch(InterruptedException e){
                        e.printStackTrace() ;
                    }
                        System.out.println(Thread.currentThread().getName()+"卖票:ticket = " + ticket++ );
                }
            }
        }
    }   
}
public class Demo{
    public static void main(String args[]){
        MyThread my = new MyThread();
        Thread d1 = new Thread(my,"窗口A");
        Thread d2 = new Thread(my,"窗口B");
        Thread d3 = new Thread(my,"窗口C");   
        Thread d4 = new Thread(my,"窗口D");
        Thread d5 = new Thread(my,"窗口E");
        Thread d6 = new Thread(my,"窗口F");
        Thread d7 = new Thread(my,"窗口G");
        Thread d8 = new Thread(my,"窗口H");
        Thread d9 = new Thread(my,"窗口I");
        Thread d10 = new Thread(my,"窗口J");
        d4.setPriority(Thread.MIN_PRIORITY) ;   
        d5.setPriority(Thread.MAX_PRIORITY) ;   
        d6.setPriority(Thread.NORM_PRIORITY) ;  
        d1.start() ;    
        d2.start() ;   
        d3.start() ;    
        d4.start() ;    
        d5.start() ;    
        d6.start() ;   
        d7.start() ;    
        d8.start() ;    
        d9.start() ;    
        d10.start() ;
    }
}

 1 对于java IO操作文件类——File的介绍与对File类主要方法与构造类的了解

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

猜你喜欢

转载自www.cnblogs.com/xzhxzh/p/11737478.html