Create and start a java thread

Source: Internet
Author: User

A java thread is an object, just like any other java object. A Thread is an instance of the java. lang. Thread class or a subclass of this class.

In java, you can create a thread as follows:


[Java]
Thread thread = new Thread ();

Thread thread = new Thread ();


You can call the start () method of this thread object to start it:

[Java]
Thread. start ();

Thread. start ();

In this example, this thread does not execute any code. Therefore, it stops immediately.

You can specify the code to be executed by the thread in two ways:

The first method is to create a subclass of a Thread and override its Run () method. The second method is to implement the Runnable () interface through an object, and rewrite the Run () method.

 


Thread subclass

The first way to specify the code to be executed for a Thread is to create a subclass of the Thread and override its run () method. This run () method will be executed by the thread after you call the satrt () method. Here is an example:

[Java]
Public class MyThread extends Thread {
Public void run (){
System. out. println ("myThread running! ");
}
}

Public class MyThread extends Thread {
Public void run (){
System. out. println ("myThread running! ");
}
}


To create and start the above thread, you can do this:

[Java]
MyThread myThread = new MyThread ();
MyThread. start ();

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


The call to the start () method stops immediately after the thread starts and waits after the run () method is executed. The Run () method is called by a different CPU. When the run () method is executed, the "MyThread running" is printed.

You can also create an anonymous Thread subclass, such:

[Java]
Thread thread = new Thread (){
Public void run (){
System. out. println ("Thread Ruuning! ");
}
}; (Translator's note: a semicolon is missing in the original text, which should be written incorrectly by the author)
Thread. start ();

Thread thread = new Thread (){
Public void run (){
System. out. println ("Thread Ruuning! ");
}
}; (Translator's note: a semicolon is missing in the original text, which should be written incorrectly by the author)
Thread. start ();


When the run () method is called by a new Thread, the "Thread Running" is printed in this example.

 


Implement the Runnable interface

The second method for specifying the code to be executed for a thread is to create a class to implement the java. lang. Runnable interface. The Runable object can be executed by a thread:


[Java]
Public class MyRunnable implements Runnable {
Public void run (){
System. out. println ("MyRunnable running! ");
}
}

Public class MyRunnable implements Runnable {
Public void run (){
System. out. println ("MyRunnable running! ");
}
}


In a Thread constructor, A MyRunnable instance allows this Thread to execute the MyRunable run () method. Let's look at the Code:

[Java]
Thread thread = new Thread (new MyRunnable ());
Thread. start ();

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


After the thread is started, it will execute the run () method of the MyRunnable instance instead of its own run () method. The above example will print "MyRunnable running! .

You can also create an anonymous class to implement the Runnable interface, such:

[Java]
Runnable myRunnable = new Runnable (){

@ Override
Public void run (){
System. out. println ("Runnable running! ");

}
}; (Translator's note: a semicolon is missing in the original text, which should be written incorrectly by the author)
Thread thread = new Thread (myRunnable );
Thread. start ();

Runnable myRunnable = new Runnable (){

@ Override
Public void run (){
System. out. println ("Runnable running! ");

}
}; (Translator's note: a semicolon is missing in the original text, which should be written incorrectly by the author)
Thread thread = new Thread (myRunnable );
Thread. start ();


Subclass or Runnable interface?

No rule specifies which of the two methods is better. Personally, I prefer to implement the Runnable interface and pass an instance that implements the Thread instance (as a parameter ). (Note: If you are not familiar with the sentence I translated, refer to the original article. Original article: I prefer implementing Runnable, and handing aninstance of the implementation to a Thread instance .) when a thread pool executes a Runnable instance, if no thread in the thread pool is idle, it is easy to queue the Runnable instance. This is difficult for the Thread subclass.

Sometimes you have to implement the Runnable interface and the Thread subclass. For example, you can create a Thread subclass to implement multiple Runnable interfaces. This method is usually used when you want to implement a thread pool.

 


Common traps: Call the run () method instead of the start () method

When creating and starting a thread, a common error is to call the run () method of the thread instead of the start () method, as shown in the following figure:

[Java]
Thread newThread = new Thread (new MyRunnable)
NewThread. run (); // this should be the start () method

Thread newThread = new Thread (new MyRunnable)
NewThread. run (); // this should be the start () method


At the beginning, you may not find any problems, because the Runable run () method is executed as expected. However, this run () method is not executed by the thread you just created (Note: it refers to the newThread object. Not the run () method executed by this thread, but the run () method creates this thread. In other words, this thread executes the above two lines of code, and the newly created thread calls the run () method of the MyRunable instance. (Translator's note: Some attackers may understand this. The first line of code creates a thread object newThread. The second line of code creates another thread. We call it tempThread for the moment. TempThread executes the run () method of the MyRunnable instance. For this newThread, you must call its start () method.

 


Thread name

When you create a thread, you can give it a name. This name allows you to distinguish it from other threads. For example, when multiple threads use System. out to output content, you can easily see which thread outputs the text. Here is an example:


[Java]
Thread thread = new Thread ("New Thread "){
Public void run (){
System. out. println ("run by:" + getName ());
}
};
Thread. start ();
System. out. println (thread. getName ());
}

Thread thread = new Thread ("New Thread "){
Public void run (){
System. out. println ("run by:" + getName ());
}
};
Thread. start ();
System. out. println (thread. getName ());
}

 

 

Note that the "New Thread" string is passed to the constructor of the Thread as a parameter. This string is the name of this thread. The thread name can be obtained through the getName () method of the thread. When you use a Runnable interface implementation, you can also pass a name to this thread. See:

[Java]
MyRunnable runnable = new MyRunnable ();
Thread thread = new Thread (runnable, "New Thread ");
Thread. start ();
System. out. println (thread. getName ());

MyRunnable runnable = new MyRunnable ();
Thread thread = new Thread (runnable, "New Thread ");
Thread. start ();
System. out. println (thread. getName ());


Note: In any case, as long as the MyRunable class is not a subclass of the Thread, it has no permission to execute the getName method of the thread. You can use the following code to obtain the currently executed thread:

[Java]
Thread. currentThread ();

Thread. currentThread ();

Obtain the name of the currently executed thread. You can do this:

[Java]
String threaName = Thread. currentThread (). getName ();

String threaName = Thread. currentThread (). getName ();

Example of a thread

Here is a small example. First, it prints the name of the thread currently executing the main () method. This thread is allocated by JVM. Then he started 10 threads and gave them a number as the name ("" + I ). Each thread then prints its own name. Then stop the execution.

 


[Java]
Public class ThreadExample {
Public static void main (String [] args ){
System. out. println (Thread. currentThread (). getName ());
For (int I = 0; I <10; I ++ ){
New Thread ("" + I ){
Public void run (){
System. out. println ("Thread:" + getName () + "running ");
}
}. Start ();
Parallel}

}

}

Public class ThreadExample {
Public static void main (String [] args ){
System. out. println (Thread. currentThread (). getName ());
For (int I = 0; I <10; I ++ ){
New Thread ("" + I ){
Public void run (){
System. out. println ("Thread:" + getName () + "running ");
}
}. Start ();
Parallel}

}
 
}

 

Note that even if threads start in order (1, 2, 3, etc.), they may not be executed in order. This means that thread1 may not be the first to write its name into System. out. This is because in principle threads are executed in parallel rather than in sequence. The JVM and (or) operating systems determine the thread execution sequence. This order is not necessarily the same as that of the threads.

 

 

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.