How Java threads are created

Source: Internet
Author: User

There are two ways in which Java creates threads

1. Implementation via Runnable interface (recommended method)

(1) Create a new class to implement the Runnable interface, you need to override the Run method

1 class Implements runnable{23    @Override4public     void run () {56    }7     8 }

(2) Create a new thread object, passing in the constructor the class that implements the Runnable interface

New Thread (new myrunnable);

(3) Call the Start method of the thread

Thread.Start ();

2. Implement by inheriting the thread class

(1) Create a new class to inherit the thread class, you need to override the Run method

1 class extends thread{2    @Override3public     void  run () {  4         Super. Run (); 5     6     }7 }

(2) call the Start method of the thread class.

New MyThread (); Thread.Start ();

3. Example

 Packagethread; Public classmultithread { Public Static voidMain (string[] args) {//1. The first method of creating a thread, using an interface to create a class that implements the interfaceRunnable Runnable =Newmyrunnable (); Thread Thread=NewThread (runnable);        Thread.Start (); //2. The second method of creating threads, using thread to open threads but not recommendedMyThread thread2 =NewMyThread ();    Thread2.start (); }}classMyrunnableImplementsrunnable{@Override Public voidrun () { for(inti = 0; i< 10; i++){            Try{System.out.println ("Use Runnable to open threads:" +i); Thread.Sleep (1000); } Catch(Interruptedexception e) {}}} }classMyThreadextendsthread{@Override Public voidrun () {Super. Run ();  for(inti = 0; I < 10; i++) {            Try{System.out.println ("Use thread to open threads:" +i); Thread.Sleep (1000); } Catch(Interruptedexception e) {} }}}

The results of the operation are as follows:

How Java threads are created

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.