Java Threads (i) Creating and starting threads

Source: Internet
Author: User

Java Threads:

A thread is a sequential flow of control within a program.

The CPU actually executes one at a point in time. It's just that we split the cup into multiple time slices, and because it's very fast, we look like multiple threads.

Just like your time is divided into several pieces, so the overall seems to do things regularly, efficiency will be high, not to mention is the cup.

To create and start a thread:

Method One:

Java threads are implemented by Java.lang.Thread classes.

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

Each thread is the tread object through its run () method to complete the operation.

Start thread mode: the start () method of thread.

For example:

public class Testthread

{

public static void Main (string[] args)

{

Runner1 r = new Runner1 ();

Defines the thread object. and calls the thread's construction method.

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 Two:

Define a subclass of the thread class, override the Run () method, and then generate the object for this class in the START 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);

}

}

}

The method of implementing interface is more flexible than two methods.

Thread Control methods:

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.