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

实验任务详情:

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

package test;

class MyThread implements Runnable{
    private int ticket =1000;
    public void run(){
        while(ticket>0){
            synchronized(this) {
                if(ticket>0) {
                    try {
                        Thread.sleep(1000);
                    }catch(InterruptedException e) {
                        e.printStackTrace();
                    }
                    ticket--;
                    System.out.println(Thread.currentThread().getName()+":售出一张票:剩余"+ticket+"张票");
                    
                    if(ticket==0) {
                        System.out.println("票已售完");
                    }
                }
            }
        }
}
}
package test;

public class SyncDemo02 {
    public static void main(String[] args) {
      MyThread mt=new MyThread();
      Thread t1=new Thread(mt,"窗口1");
      Thread t2=new Thread(mt,"窗口2");
      Thread t3=new Thread(mt,"窗口3");
      Thread t4=new Thread(mt,"窗口4");
      Thread t5=new Thread(mt,"窗口5");
      Thread t6=new Thread(mt,"窗口6");
      Thread t7=new Thread(mt,"窗口7");
      Thread t8=new Thread(mt,"窗口8");
      Thread t9=new Thread(mt,"窗口9");
      Thread t10=new Thread(mt,"窗口10");
      t1.start();
      t2.start();
      t3.start();
      t4.start();
      t5.start();
      t6.start();
      t7.start();
      t8.start();
      t9.start();
      t10.start();
}
}

 

 

 

 这次作业主要是通过看书完成的,感觉自己还有很多不会的地方。为了快速运行所以把休眠时间改成了1毫秒。

 

 

  jave中实现多线程手段有两种

1.继承Thread类

2.实现Runnable接口

posted @ 2019-10-25 21:51  时光碎片  阅读(138)  评论(0编辑  收藏  举报