2019秋JAVA第三周课程总结及实验报告(七)

实验七

实验任务详情:

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

 

实验代码

Main.java

 1 public class Main
 2 {
 3     public static void main(String[] args) {
 4         Thr t = new Thr();
 5 
 6         new Thread(t).start();
 7         new Thread(t).start();
 8         new Thread(t).start();
 9         new Thread(t).start();
10         new Thread(t).start();
11         new Thread(t).start();
12         new Thread(t).start();
13         new Thread(t).start();
14         new Thread(t).start();
15         new Thread(t).start();
16     }
17 
18 }

 

Thr.java

 1 package New.Learn;
 2 
 3 public class Thr implements Runnable {
 4     private int ticket = 100;
 5     private final Object lock = new Object();
 6 
 7     Thr(){
 8     }
 9 
10     @Override
11     public void run() {
12         while (true){
13             synchronized(lock){
14                 if (ticket>0){
15                     try {
16                         Thread.sleep(10);
17                         System.out.println("窗口: "+ Thread.currentThread().getName() + "正在卖第" + ticket + "张票");
18                         ticket--;
19                     }catch (InterruptedException e){
20                         e.printStackTrace();
21                     }
22 
23                 }
24 
25                 else {
26                     break;
27                 }
28 
29 
30             }
31         }
32 
33 
34 
35     }
36 }

 

总结

多线程编程要想提升效率需要对流程有详细了解,目前写的多线程程序都没能实现效率的提升。

posted @ 2019-10-24 16:54  harsonyoung  阅读(124)  评论(0)    收藏  举报