(售票)线程小练习

 1 package com.ccp.Lc0814;
 2 
 3 public class Ticket {
 4     char c;//用户
 5     boolean is=false;
 6     public synchronized void ticket1(char c) throws InterruptedException {
 7         if (is){
 8             System.out.println("有票了,快抢票。。。");
 9             wait();
10         }
11         this.c=c;
12         is=true;
13         System.out.println("马上去抢票,快跑!!!next"+this.c);
14         notify();
15     }
16     public synchronized char ticket2() throws InterruptedException {
17         if (!is){
18             System.out.println("看看余票还有没有。。。");
19             wait();
20         }
21         System.out.println("抢到了,Happly!!!"+c);
22         is=false;
23         notify();
24         return c;
25     }
26 }
27 ———————————————————————————————————————
28 package com.ccp.Lc0814;
29 
30 public class TicketConsumer implements Runnable{
31 Ticket ticket;
32 
33     public TicketConsumer(Ticket ticket) {
34         this.ticket=ticket;
35     }
36 
37     public TicketConsumer() {
38     }
39 
40     @Override
41     public void run() {
42         char c='A';
43         do {
44         try {
45             Thread.sleep(1000);
46             c=ticket.ticket2();
47         } catch (InterruptedException e) {
48             e.printStackTrace();
49         }
50         }while (c!='D');
51     }
52 }
53 ————————————————————————————————————————
54 package com.ccp.Lc0814;
55 
56 public class TicketProducer implements Runnable{
57     Ticket ticket;
58 
59     public TicketProducer() {
60     }
61 
62     public TicketProducer(Ticket ticket) {
63         this.ticket=ticket;
64     }
65 
66     @Override
67     public void run() {
68         for (char c='A'; c<='D'; c++) {
69             try {
70                 Thread.sleep(1000);
71                 ticket.ticket1(c);
72             } catch (InterruptedException e) {
73                 e.printStackTrace();
74             }
75         }
76     }
77 }
78 ————————————————————————————————————————
79 package com.ccp.Lc0814;
80 
81 public class TicketStart {
82     public static void main(String[] args) {
83         Ticket ticket=new Ticket();
84         TicketConsumer ticketConsumer=new TicketConsumer(ticket);
85         TicketProducer ticketProducer=new TicketProducer(ticket);
86         Thread thread1=new Thread(ticketConsumer);
87         Thread thread2=new Thread(ticketProducer);
88         thread1.start();
89         thread2.start();
90     }
91 
92 
93 }

 

posted on 2019-08-16 08:26  年夜饭  阅读(113)  评论(0编辑  收藏  举报

导航