Ticket Selling problem: there are 50 tickets that need to be sold in three windows; use two ways to sell tickets in two ways, observe what the results of the two ways to sell tickets are different.
Class Ticket1 extends Thread {int num = 50; // 50 tickets Ticket1 (String name) {super (name) ;}public void run () {for (int I = 0; I <200; I ++) {if (num> 0) {System. out. println (getName () + "sold" + num -- + "tickets") ;}}} public class TicketDemo1 {public static void main (String [] args) {new Ticket1 (""). start (); new Ticket1 ("B "). start (); new Ticket1 ("C "). start ();}}
Inheritance Method: After running, it is found that 50 tickets are sold in each window, which does not meet the requirements of the question.
Class Ticket2 implements Runnable {int num = 50; @ Overridepublic void run () {for (int I = 0; I <200; I ++) {if (num> 0) {System. out. println (Thread. currentThread (). getName () + "sold" + num -- + "tickets") ;}}} public class TicketDemo2 {public static void main (String [] args) {Runnable target = new Ticket2 (); new Thread (target, ""). start (); new Thread (target, "B "). start (); new Thread (target, "C "). start ();}}
Implementation Method: basically meets the requirements of the question
Comparison:
1) The Inheritance method is used, and resources cannot be shared or inherited. After inheriting the Thread class, other classes cannot be inherited, but the inheritance method is simpler.
2) It is recommended to use interface methods to facilitate future expansion and resource sharing.