Java multi-thread (2), three ways to start a thread

Source: Internet
Author: User
Package Org. study. thread;/*** three ways to start a thread */public class traditionalthread {public static void main (string [] ARGs) {// 1. inherited from the Thread class (here the Anonymous class is used) New thread () {@ overridepublic void run () {While (true) {try {thread. sleep (500);} catch (interruptedexception e) {e. printstacktrace ();} system. out. println ("threadname:" + thread. currentthread (). getname ());}};}. start (); // 2. implement the runnable interface (here the Anonymous class is used) New thread (New runnable () {@ overridepublic void run () {While (true) {try {thread. sleep (500);} catch (interruptedexception e) {e. printstacktrace ();} system. out. println ("threadname:" + thread. currentthread (). getname ());}}}). start (); // 3. that is, to implement the runnable interface, inherit the Thread class, and override the run method new thread (New runnable () {@ overridepublic void run () {// implement the runnable interface while (true) {try {thread. sleep (500);} catch (interruptedexception e) {e. printstacktrace ();} system. out. println ("implements runnable thread:" + thread. currentthread (). getname () ;}}) {// inherits the Thread class @ overridepublic void run () {While (true) {try {thread. sleep (500);} catch (interruptedexception e) {e. printstacktrace ();} system. out. println ("extends thread:" + thread. currentthread (). getname ());}}}. start ();}}

Execution result:

Threadname: thread-0

Threadname: thread-1

Extends thread: thread-2

Threadname: thread-1

Threadname: thread-0

Extends thread: thread-2

Threadname: thread-1

Threadname: thread-0

Extends thread: thread-2

...

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.