Java Concurrency Series-5, how to create and run Java thread __java

Source: Internet
Author: User
Tags thread class
The Java thread class is also an object class, and its instances inherit from Java.lang.Thread or its subclasses. You can create a thread in Java in the following ways:
Tread thread = new Thread ();
Executing this thread can invoke the start () method of the thread:
Thread.Start ();
In the above example, we did not write the code for the thread, so the thread terminates when the method is invoked.

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

to create a subclass of thread

Creates an instance of the thread subclass and overrides the Run method, which is executed after the start () method is invoked. 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 subclass in the following ways

Mythread mythread = new Mythread ();
Mytread.start ();

Once the thread starts, the Start method returns immediately without waiting until the Run method has finished executing. It's like the Run method executes on another CPU. When the Run method executes, the string mythread running is 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 method in the instance can be invoked by the thread. Here's an example:

public class Myrunnable implements Runnable {public
   void run () {
    System.out.println ("myrunnable running");
   }
}
In order for the thread to execute the run () method, you need 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 runs, it invokes the Run method that implements the Runnable interface. The "myrunnable running" will be printed in the example above.

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 the Runnable interface.

There is no definite answer as to which of these two approaches is good, and they all satisfy the requirements. My personal opinion, I am more inclined to implement Runnable interface this 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 would be more complicated if the thread was implemented by implementing the thread subclass.

Sometimes we have to combine the implementation of the Runnable interface and thread subclass two ways. 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: Invoke the Run () method rather than the start () method

The common mistake of creating and running a thread is to invoke the thread's run () method rather than the start () method, as follows:

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

You won't feel anything wrong at first, because the run () method is actually invoked as you wish. However, in fact, the run () method was not executed by the new thread that was just created, but by the current thread that created the new thread. Which is executed by the thread executing the above two lines of code. To make the new thread you create 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 distinguish between different threads. For example, if more than one thread writes to System.out, we can easily find out which thread is outputting 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 should be noted that because myrunnable is not a subclass of thread, the Myrunnable class does not have the 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 using the following code:
String threadname = Thread.CurrentThread (). GetName ();
Thread code example:
Here is a small example. The first output executes the main () method thread name. This thread JVM is assigned. Then open 10 threads, named 1~10. Each thread outputs its own name and exits.
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 should be noted that although the order of the boot threads is ordered, the order of execution is not sequential. In other words, Route Line 1 is not necessarily the first thread to export its name to the console. This is because threads are executed in parallel, not sequentially. Together, the JVM and the operating system determine the order in which threads are executed, and the order in which they are started is not necessarily consistent.

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.