Java basic review: thread Exercise 1

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.