Two ways to implement multithreading in Java

Source: Internet
Author: User
Tags instance method

1: Inheriting the Therad class
2: Implement Runnable interface

1, inherit the thread class to realize multithreading
Methods of inheriting the thread class although I am listed as a multithreaded implementation, thread is essentially an instance of implementing the Runnable interface, which represents an instance of a thread, and the only way to start a thread is through the start () instance method of the thread class. The start () method is a native method that starts a new thread and executes the run () method. This way of implementing multithreading is simple, by extend thread directly through your own class, and by copying the run () method, you can start a new thread and execute your own defined run () method. For example:

 Public class extends  Thread {  publicvoid  run () {System.out.println ("Mythread.run ()"); }}


Start the thread in the appropriate place as follows:

Newnew  MyThread (); Mythread1.start (); Mythread2.start ();

2, realize the Runnable interface way to realize multithreading
If your class already extends another class, you cannot directly extends the Thread, at which point you must implement a runnable interface, as follows:

 Public class extends Implements  Runnable {  publicvoid  run () {System.out.println ("Mythread.run ()"); }}

In order to start mythread, you need to instantiate a thread first and pass in your own Mythread instance:

Newnew  Thread (myThread); Thread.Start ();

In fact, when a runnable target parameter is passed to thread, the thread's Run () method calls Target.run (), referencing the JDK source code:

 Public void  run () {  ifnull) {target.run (); }}

Two ways to implement multithreading in Java

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.