. 1 Package com.ccp.Lc0814; 2 . 3 public class Ticket { . 4 char C; // user . 5 Boolean IS = to false ; . 6 public the synchronized void ticket1 ( char C) throws InterruptedException { . 7 IF ( IS ) { . 8 the System. OUT . the println ( " tickets, the ticket Kuaiqiang ... " ); . 9 the wait (); 10 } . 11 the this .c =C; 12 is IS = to true ; 13 is . the System OUT .println ( " immediately grab votes, Run Next !!! " + the this .c); 14 Notify (); 15 } 16 public the synchronized char ticket2 () throws InterruptedException { 17 IF (! IS ) { 18 System. OUT .println ( " look I vote there is no ... " ); 19 the 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 }