Java thread (1) Create and start a thread

Source: Internet
Author: User

Java thread:

A thread is the sequential control flow within a program.

The CPU actually executes only one task at a time point. However, we divide the CPU into multiple time slices. Because of the high speed, we seem to have multiple threads ..

 

Just like dividing your time into several slices, it seems that the efficiency will be high if you do things regularly, not to mention the cup.

 

Thread creation and startup:

Method 1:

Java threads are implemented through the java. Lang. Thread class.

The VM starts with a thread defined by the main method,

Each thread is a tread object that uses its run () method to complete operations.

Thread start method: Start () method of thread.

 

For example:

Public class testthread

{

 

Public static void main (string [] ARGs)

{

Runner1 r = new runner1 ();

// Define the thread object. And call the thread constructor.

Thread t = new thread (R );

// Start the thread.

T. Start ();

 

For (INT I = 0; I <100; I ++)

{

System. Out. println ("main thread -----" + I );

}

 

}

 

}

 

Class runner1 implements runnable

{

Public void run ()

{

For (INT I = 1; I <100; I ++)

{

System. Out. println ("runner1" + I );

}

}

}

Method 2:

Define a subclass of the thread class, override the run () method, and then generate the object of this class, and start the process.

 

Public class testthread

{

 

Public static void main (string [] ARGs)

{

Runner1 r = new runner1 ();

// Start the thread.

R. Start ();

 

For (INT I = 0; I <100; I ++)

{

System. Out. println ("main thread -----" + I );

}

 

}

 

}

 

Class runner1 extends thread

{

Public void run ()

{

For (INT I = 1; I <100; I ++)

{

System. Out. println ("runner1" + I );

}

}

}

 

Compared with the two methods, the method for implementing interfaces is more flexible.

 

 

Thread control method:

 

 

Related Article

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.