How to create a Java multi-threading method

Source: Internet
Author: User

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 way, and the thread can invoke the start () method of that thread:

Tread thread = new 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 a subclass of Thread

Creating an instance of the Thread subclass and overriding the Run method, the Run method is executed after the start () method is called. Examples of the above Thread subclasses can be created and run as follows:

public class MyThread extends Thread {

public void Run () {

System.out.println ("MyThread running");

}

}

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".

Implementing the 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 (newmyrunnable ());

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: Calling the Run () method rather than the 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 = Newthread (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 ();

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 here that although the order in which the threads are started is sequential, the order of execution is not sequential. 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.

How to create a Java multi-threading 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.