How to create and run a Java thread

Source: Internet
Author: User

Original link Translator: Zhang proofreading: Fang Fei

The Java thread class is also an object class, and its instances are inherited from Java.lang.Thread or its subclasses. You can create a thread in Java in the following ways:

Tread thread = new Thread ();

Executing the thread can invoke the start () method of the thread:

Thread.Start ();


In the example above, we did not run the code for the thread, so the thread terminated when the method was called.

There are two ways to write code that executes when the thread runs: one is to create an instance of the thread subclass and override the Run method, and the second is to implement the Runnable interface when creating the class. Next we will explain the two methods in detail:

Create thread sub-class

Creating an instance of the thread subclass and overriding the Run method, the Run method is executed after the start () method is called. Examples are as follows:

public class MyThread extends Thread {public   void run () {     System.out.println ("MyThread Running");}   }

You can create and run the above thread subclasses in the following ways

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

Once the thread is started, the Start method returns immediately without waiting until the Run method has finished executing. It is as if the Run method is executed on a different CPU. When the Run method executes, the string mythread running will be printed.

You can also create an anonymous subclass of thread as follows:

Thread thread = new Thread () {public   void run () {     System.out.println ("Thread Running");   }}; Thread.Start ();

When the new thread's Run method executes, the computer prints out the string "Thread Running".

Implement Runnable Interface

The second way to write thread execution code is to create an instance of a class that implements the Java.lang.Runnable interface, and the methods in the instance can be called by the thread. Here's an example:

public class Myrunnable implements Runnable {public   void run () {    System.out.println ("myrunnable Running");}   }

In order for a thread to execute the run () method, it is necessary to pass in the Myrunnable instance object in the constructor of the thread class. Examples are as follows:

Thread thread = new Thread (new myrunnable ()); Thread.Start ();

When the thread is running, it will call the Run method that implements the Runnable interface. In the example above, "myrunnable running" will be printed out.

Similarly, you can create an anonymous class that implements the Runnable interface as follows:

Runnable myrunnable = new Runnable () {public   void run () {     System.out.println ("Runnable Running");}   } Thread thread = new Thread (myrunnable); Thread.Start ();

Create a subclass or implement a runnable interface?

There is no definite answer to either of these two ways, and they all meet the requirements. As far as my personal opinion is, I prefer to implement the Runnable interface method. Because the thread pool can effectively manage the threads that implement the Runnable interface, if the thread pool is full, the new thread is queued for execution until the thread pool is idle. This can be complicated if the thread is implemented by implementing the thread subclass.

Sometimes we need to combine the implementation of the Runnable interface and thread subclass in two ways at the same time. For example, an instance that implements the thread subclass can execute multiple threads that implement the Runnable interface. A typical application is the thread pool.

Common error: Call run () method rather than start () Method

A common mistake that is made to create and run a thread is to call the thread's run () method instead of the start () method, as follows:

Thread newthread = new Thread (myrunnable ()); Newthread.run (); should be start ();

At first you don't feel anything wrong, because the run () method is actually called as you wish. However, in fact, the run () method is not executed by the new thread that was just created, but by the current thread that created the new thread. That is, executed by the thread executing the above two lines of code. To have the new thread created execute the Run () method, you must call the new thread's Start method.

Thread Name

When creating a thread, you can give the thread a name. It helps us to differentiate between different threads. For example, if more than one thread writes to System.out, we can easily find out which thread is outputting it through the thread name. Examples are as follows:

Myrunnable runnable = new myrunnable (); Thread thread = new Thread (runnable, "new Thread"); Thread.Start (); System.out.println (Thread.getname ());

It is important to note that because Myrunnable is not a subclass of thread, the Myrunnable class does not have a getname () method. You can get a reference to the current thread in the following ways:

Thread.CurrentThread ();

Therefore, the name of the current thread can be obtained by the following code:

String threadname = Thread.CurrentThread (). GetName ();

Example Thread code:
Here is a small example. First the output executes the main () method thread name. This thread is allocated by the JVM. Then turn on 10 threads, named 1~10. Each thread exits after it prints its own name.

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 ();}}  }

It is important to note that although the order in which the threads are started is sequential, the order of execution is not orderly. That is, line Line 1 is not necessarily the first thread to output its name to the console. This is because threads are executed in parallel rather than sequentially. The JVM and the operating system together determine the order in which the threads are executed, and the order in which he and the threads are started is not necessarily consistent.

(full text) If you like this article please click to praise, share, comment.

How to create and run a Java thread

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.