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

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

package nine;

class MyThread implements Runnable{             
    private int ticket=1000;
    public void run() {                                      
        for(int i=0;i<1000;i++) {
            synchronized(this) {                   
                if(ticket>0) {                          
                    try {
                        Thread.sleep(1000);
                    }
                    catch(Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"售票:"+ticket--);    
                }
            }
        }
    }
};
public class Test{
    public static void main(String[] args) {
        MyThread b=new MyThread();             
        new Thread(b,"窗口1").start();         
        new Thread(b,"窗口2").start();
        new Thread(b,"窗口3").start();
        new Thread(b,"窗口4").start();
        new Thread(b,"窗口5").start();
        new Thread(b,"窗口6").start();
        new Thread(b,"窗口7").start();
        new Thread(b,"窗口8").start();
        new Thread(b,"窗口9").start();
        new Thread(b,"窗口10").start();
    }
}

总结:
1、学习多线程的使用。
2、了解并编写现实中应用的事物,像刚写的火车站售票原理。
3、学习了file,在指定文件夹中创建新的文件夹或文本文档。

心得:
学习Java使我快乐,加油!!争取学到更多。

猜你喜欢

转载自www.cnblogs.com/ZhangGuang29/p/11720000.html