Java 多线程练习 三人共抢10张票 限制黄牛党只能抢到一张票

|--需求说明

|--实现方式

在run()方法里面写一个while循环,循环体里面执行一个加过synchronized的方法,这个方法下面加一个判断语句,当线程名为“黄牛党”的时候,退出这个线程

|--代码内容 

 1 package cn.thread1;
 2 
 3 import java.util.Enumeration;
 4 
 5 /**
 6  * @auther::9527
 7  * @Description: 看病
 8  * @program: shi_yong
 9  * @create: 2019-08-05 14:34
10  */
11 public class Patient implements Runnable {
12     private String name;
13     private int num = 0;    //抢的票
14     private int count = 10;  //总票数
15     private boolean flag = false;  //记录票是否买完
16 
17     public Patient() {
18     }
19 
20     public Patient(String name) {
21         this.name = name;
22     }
23 
24     @Override
25     public void run() {
26         while (!flag) {
27             tickets();
28             //如果黄牛党抢票,就退出循环
29             if (Thread.currentThread().getName().equals("黄牛党")){
30                 return;
31             }
32         }
33 
34     }
35 
36     public synchronized void tickets() {
37         //设置循环终止条件
38         if (count <= 0) {
39             flag = true;
40             return;
41         }
42         //每循环一次,总票数减一,抢到的票数加一
43         count--;
44         num++;
45         try {
46             //模拟网络延迟
47             Thread.sleep(100);
48         } catch (InterruptedException e) {
49             e.printStackTrace();
50         }
51         //按需求输出信息
52         System.out.println(Thread.currentThread().getName()+"抢到了第"+num+"张票,剩余"+count+"张票!");
53 
54     }
55 }
线程类
 1 package cn.thread1;
 2 
 3 /**
 4  * @auther::9527
 5  * @Description: 运行
 6  * @program: shi_yong
 7  * @create: 2019-08-05 15:00
 8  */
 9 public class Main {
10     public static void main(String[] args) {
11         Patient p = new Patient();
12 
13         Thread t1 = new Thread(p,"桃跑跑");
14         Thread t2 = new Thread(p,"张票票");
15         Thread t3 = new Thread(p,"黄牛党");
16         t1.start();
17         t2.start();
18         t3.start();
19     }
20 }
程序入口

|--运行结果

 |--错误记录

最开开始的时候,判断抢票人的方法写在run()方法外面,一直没有实现需求,

 如下所示,如果判断在输出信息前,就会导致票没抢完就程序终止

猜你喜欢

转载自www.cnblogs.com/twuxian/p/11304045.html