Several ways to create a thread and several ways to create a thread

Source: Internet
Author: User

Several ways to create a thread and several ways to create a thread

Speaking of threads, you will surely think of using the java. lang. Thread. java class.

There are two main ways to create a thread:

Method 1:

Public class MyThread extends Thread {public void run () {System. out. println ("this is MyThread Thread ");}}

Then, execute the start method at the call:

MyThread myThread = new MyThread();myThread.start();

The second method implements the Runnable interface:

Public class MyRunnable implements Runnable {public void run () {System. out. println ("this is MyThread thread ");
}
}

Similarly, the MyRunnable can be directly lived in the execution place, and then directly thrown into the thread start:

MyRunnable runBary = new MyRunnable();Thread thread = new Thread(runBary);thread.start();

Both methods can be implemented using anonymous classes, but I do not recommend them;

In addition, using the Thread itself to implement the Thread is still implemented using Runnable. I recommend the latter because it is relatively convenient and can be directly thrown into the Thread, if you use the spring thread actuator, you can just drop this runnable into the actuator.

Note that the start () method or run () method can be used to execute a thread. Although run can achieve the same effect,

But run is used in the main thread, that is, to use the thread in your current method, rather than starting another thread, so that the asynchronous effect is not achieved, so be sure to use start ()

 

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.