1 Public classSellticketdemo {2 Public Static voidMain (string[] args) {3 //Create three thread objects4Sellticket St1 =NewSellticket ();5Sellticket St2 =NewSellticket ();6Sellticket ST3 =NewSellticket ();7 8 //name a Thread object9St1.setname ("Windows 1");TenSt2.setname ("Windows 2"); OneSt3.setname ("Windows 3"); A - //Start Thread - St1.start (); the St2.start (); - St3.start (); - } - } + Public classSellticket extends Thread { - + //Define 100 Tickets A //private int tickets = +; at //in order for multiple thread objects to share these 100 tickets, we should actually use static retouching - Private Static intTickets = -; - - @Override - Public voidrun () { - //Define 100 Tickets in //each thread comes in and goes here, so that each thread object is equivalent to buying the 100 tickets of its own, which is unreasonable, so it should be defined outside - //int tickets = +; to + //is to simulate the always having tickets - while(true) { the if(Tickets >0) { *System. out. println (GetName () +"is selling"+ (tickets--) +"Ticket"); $ }Panax Notoginseng } - } the}
1 Public classSellticketdemo {2 Public Static voidMain (string[] args) {3 //Create a Resource object4Sellticket st =NewSellticket ();5 6 //Create three thread objects7Thread T1 =NewThread (St,"Windows 1");8Thread t2 =NewThread (St,"Windows 2");9Thread t3 =NewThread (St,"Windows 3");Ten One //Start Thread A T1.start (); - T2.start (); - T3.start (); the } - } - Public classSellticket implements Runnable { - //Define 100 Tickets + Private intTickets = -; - + @Override A Public voidrun () { at while(true) { - if(Tickets >0) { -System. out. println (Thread.CurrentThread (). GetName () +"is selling" -+ (tickets--) +"Ticket"); - } - } in } -}
In both of these ways the result will be problematic negative votes .... ->>>>
Java note Thread simulates the cinema selling tickets in two ways