Java basics: thread Creation

Source: Internet
Author: User

Creation thread:

(1) Method 1: Inheritance

 
/** Thread creation method: Inherit Thread class * 1) create a class and inherit thread * 2) overwrite the run Method * 3) create a thread object * 4) start the thread (thread object. start () **/class mythread extends thread {public mythread (string name) {super (name) ;}@ overridepublic void run () {// thread body for (INT I = 0; I <100; I ++) {system. out. println (super. getname () + I) ;}} public class threaddemo {public static void main (string [] ARGs) {for (INT I = 0; I <200; I ++) {string name = thread. currentthread (). getname (); system. out. println (name + "---->" + I); if (I = 50) {New mythread ("well "). start ();}}}}

(2) Method 2: implementation

/** 1. define a class to implement the runnable interface * 2. implementation of the run Method * 3. create a new thread (runnable object) * 4. call the start method of the thread class */class mythread2 implements runnable {@ overridepublic void run () {for (INT I = 0; I <100; I ++) {string name = thread. currentthread (). getname (); system. out. println (name + "---->" + I) ;}} public class threaddemo2 {public static void main (string [] ARGs) {for (INT I = 0; I <args. length; I ++) {system. out. println ("Main -->" + I); if (I = 10) {New thread (New mythread2 (), "hello "). start ();}}}}

Currentthread () returns a reference to the currently executed thread object.

Getname () gets the thread name

Setname () sets the thread name

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.