Create multithreaded mode two (implement Runnable interface)

Source: Internet
Author: User
Tags thread class

steps:

1. Define the class implementation runnable interface.
2. Overwrite the Run method in the interface. Define the thread task code in the Run method.
3. Create an object of the thread class.
4. Pass the subclass object of the Runnable interface as a parameter to the constructor of the thread class.
5. Call the Start method of the thread class to open the thread.

Instance:

classDemoImplementsrunnable{PrivateString name;  PublicDemo (String name) { This. Name =name; } Public voidrun () { for(inti = 0; I < 20; i++) {System.out.println (name+ ".." + Thread.CurrentThread (). GetName () + "..." +i); }}} Public classThreadDemo2 { Public Static voidMain (string[] args) {Demo d=NewDemo ("Demo"); Thread T=NewThread (d); Thread T2=NewThread (d);    T.start ();    T2.start (); System.out.println (Thread.CurrentThread (). GetName ()+ "***");//The main thread executes once at the beginning and then does not execute.     }}

Benefits of this approach:

1. Implementing runnable interface avoids the limitation of single inheritance, so it is more commonly used.
2. The way to implement the Runnable interface, more conform to object-oriented, the thread is divided into two parts, part of the thread object, part of the thread task.

Inherit the thread class: The Run method is in thread. The thread object and the thread task are coupled together. Once the child class object of the thread class is created, it is both a thread object and a threaded task.
Implement the Runnable interface: The Run method is in runnable. Separate the thread tasks into objects (Runnable interface types), use runnable to identify thread tasks, and thread to define threading objects. The Runnable interface decouples thread objects and thread tasks.

Create multithreaded mode two (implement Runnable interface)

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.