Home > Java > javaTutorial > body text

Create and start a Java thread

黄舟
Release: 2017-02-28 10:29:57
Original
1439 people have browsed it

Java thread is an object type similar to any other object. A thread is an instance of the java.lang.Thread class, or an instance of a subclass of this class. In addition to being an object type, Java threads can also execute code.

Create and start a thread

Create a thread like this:

Thread thread = new Thread();
Copy after login

To start a Java thread, you The start method needs to be called, like the following:

thread.start();
Copy after login

This example does not specify any code that the thread will execute. This thread will be stopped immediately after it is started.

There are two ways to specify what code this thread should execute. The first method is to create a subclass of thread and then override the run() method. The second method is to pass an object that implements the Runnable interface to the Thread constructor. Both methods are mentioned below.

Thread Subclass

The first way to specify what code a thread will run is to create a subclass of the thread and Override the run() method. This run() method is executed by this thread after you call the start() method. Here is an example:

public class MyThread extends Thread {

    public void run(){
       System.out.println("MyThread running");
    }
  }
Copy after login

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

 MyThread myThread = new MyThread();
  myTread.start();
Copy after login


As soon as the thread is started, the start() method will return. It will not wait until the run() method ends. This run() method will be executed by different CPUs. When this run() method is executed, it will print out the text content "MyThread running".

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

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

  thread.start();
Copy after login


The running results of this example will be the same as above.

Runnable interface implementation

The second way to specify what code a thread should run is by creating an implementation of the java.lang.Runnable interface of a class. This Runnable object can be executed by a thread.

Here is an example:

public class MyRunnable implements Runnable {

    public void run(){
       System.out.println("MyRunnable running");
    }
  }
Copy after login

In order for the run method to be executed by a thread, you need to pass a MyRunnable instance to the constructor of a thread. Here is an example:

Thread thread = new Thread(new MyRunnable());
   thread.start();
Copy after login

When this thread starts, it will call the run method of MyRunnable instead of executing its own run method. The above example will print the text "MyRunnable running".

You can also create an anonymous implementation like this:


Runnable myRunnable = new Runnable(){

     public void run(){
        System.out.println("Runnable running");
     }
   }

   Thread thread = new Thread(myRunnable);
   thread.start();
Copy after login


Inherit Thread or implement the interface?

There are no rules here as to which of the two methods is best. Both ways will work. However, for me personally, I prefer to implement the Runnable interface and manage instances of this implementation as a Thread instance. When there is a Runnable implementation that is executed by a thread pool, it is simple to queue Runnable instances until threads from the pool are free. This is a bit difficult to achieve using a Thread subclass.

Usually you not only need to implement Runnable, but also implement the subclass Thread. For example, if you create a Thread subclass you can execute more than one Runnable. This is a typical example of implementing a thread pool.

Common pitfall: calling run() instead of start()

When creating and starting a thread, a common mistake is to call Thread's run method replaces the start method, like the following:

Thread newThread = new Thread(MyRunnable());
  newThread.run();  //should be start();
Copy after login

First of all, you may not notice anything, because Runnable's run method will also execute as you expect. However, it will not be executed by the new thread you create. The run method of the thread that replaced the thread that created it is executed. In other words, the thread on which the above two lines of code execute. In order for the run method of the newly created thread instance to be called, you must call the start method.

Thread name

When you create a java thread, you can give it a name. This name helps you distinguish between different threads. For example, if multiple threads write this output, it can be seen which thread wrote which text. Here is an example:

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


   thread.start();
   System.out.println(thread.getName());
Copy after login


Note the character channel parameter passed to the Thread constructor. This string is the name of the thread. This name can be obtained through Thread's getName method. When running a Runnable implementation, you can also pass a name. Like the following:

MyRunnable runnable = new MyRunnable();
   Thread thread = new Thread(runnable, "New Thread");

   thread.start();
   System.out.println(thread.getName());
Copy after login


However, be aware that because the MyRunnable class is not a subclass of the Thread class, it cannot access the getName() method of the thread that is executing it.

Thread.currentThread()

This method returns a reference to the Thread instance of the current thread being executed. This way you can access the Thread object of the thread that is executing the block of code. Here's an example:

Thread thread = Thread.currentThread();
Copy after login


Once you have a reference to a Thread object, you can call methods on it. For example, you can get the name of the thread executing:

String threadName = Thread.currentThread().getName();
Copy after login


Java Thread Instance

这里有一个小的例子。首先它打印出来了正在执行的main方法的线程的名字。这个线程是被JVM分配的。然后启动了10个线程,以及给予他们所有作为名称(“”+i)的一个数字。每一个线程然后打印出名字,以及停止执行。

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


注意,甚至如果线程是按顺序启动的(1,2,3等等)。他们可能也不会按顺序执行的,意味着线程1可能不是第一个打印出来的名字。这个就是为什么原则上线程是并行运行而不是顺序呢执行的原因了。这个JVM以及操作系统决定着线程执行的顺序。这个顺序每次在他们启动的时候都不会相同的。
以上就是创建以及启动一个Java线程的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!