不安全线程取票

 1 package 多线程练习;
 2 
 3 public class 不安全线程买票实例 {
 4     public static void main(String[] args) {
 5         BuyTicket bt = new BuyTicket();
 6         new Thread(bt, "小明").start();
 7         new Thread(bt, "王老师").start();
 8         new Thread(bt, "黄牛党").start();
 9     }
10 }
11 
12 
13 /*
14    模拟一个买票的线程接口实现类
15  */
16 class BuyTicket implements Runnable {
17 
18     private int ticket = 10;
19     private Boolean flag = true;
20 
21     @Override
22     public void run() {
23         while (flag) {
24             buy();
25         }
26     }
27 
28     /*
29        买票方法
30      */
31     public void buy() {
32         // 票卖完了
33         if (ticket <= 0) {
34             flag = false;
35             return;
36         }
37 
38         // 模拟延时
39         try {
40             Thread.sleep(100);
41         } catch (InterruptedException e) {
42             e.printStackTrace();
43         }
44 
45         //模拟买票
46         System.out.println(Thread.currentThread().getName() + " 买到了第 " + ticket-- + " 张表");
47     }
48 }

 

输出结果

 

 

 

 

 

posted @ 2022-01-15 17:33  Chris丶Woo  阅读(21)  评论(0编辑  收藏  举报