Creating threads in Java

Source: Internet
Author: User

There are in general two ways to create and start a new thread in Java.

1. Extend the Thread class and override the run () method

 
Public class mythread extends thread {@ override public void run () {// define your task here }}

2. Implement the runnable interface

 
Public class myrunnable implements runnable {@ override public void run () {// define your task here }}

Then how to start a new thread

For the first way

 
Mythread thread = new mythread (); thread. Start (); // start will eventually call the run () method of the thread instance

For the second way

Myrunnable runnable = new myrunnable (); New thread (runnable). Start (); // start will eventually call the run () method of the myrunnable instance

In fact, if we check the source of the thread class, it will be something like this

 
Public class thread implements runnable {private runnable target; Public thread (runnable TAR) {this.tar get = tar;} public void start () {// some magic code which will eventually call run ()} public void run () {if(this.tar get! = NULL) {this.tar get. Run ();}}}

Now we can understand the two ways of creating threads, the first way simply uses Runtime polymorphism, and the second way is even more straightforward.

Note: Please do not directly call thread. run () or runnable. run () If you have CT some parallel execution. as the direct callwill make the code synchronously executed in the current thread, in fact the mythread and myrunnable are simply two classes with nothing
Special. There are some pieces of code in the thread. Start () which can magically create new threads.

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.