Java concurrency Programming (6): runnable and thread to achieve the difference between multithreading (including code) __java

Source: Internet
Author: User
Tags thread class ticket

There are two ways to implement multithreading in Java: To inherit the thread class and implement the Runnable interface, as long as it is multi-threaded in the development of the program, it is always to realize the runnable interface, because the implementation of the Runnable interface has the following advantages over the inheritance thread class:

1, can avoid the single inheritance of Java because of the limitations caused by the characteristics;

2, enhance the robustness of the program, code can be shared by multiple threads, the code and data is independent;

3. A thread area that is suitable for multiple identical program codes handles the same resource.

The following is an example of a typical ticket-buying process (basically taking this as an example) to illustrate the difference.

The code is implemented first by inheriting the thread class:

class Mythread extends Th read{     private int ticket = 5      public void Run () {   &nbs p;     for (int i= 0;i< i++)          {              if (Ticket > 0) {                  System.out.println ("ticket =" + ticket--);             }          }   &n
1 2 3 4 5 6 7 8 9 () '
Related Article

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.