Examples of two methods of implementing multithreading in JAVA are Shared

  • 2020-04-01 02:08:59
  • OfStack

The Java language already has built-in multithreading support, and all classes that implement the Runnable interface can be started with a new thread that executes the instance's run() method, which ends when the run() method is executed. Once a thread has finished executing, the instance cannot be restarted, only a new instance can be generated and a new thread can be started.
The Thread class is an instance that implements the Runnable interface, which represents an instance of a Thread, and the only way to start a Thread is through the start() instance method of the Thread class:

  Thread t = new Thread();
  t.start();

The start() method is a native method that starts a new thread and executes the run() method. The default run() method of the Thread class exits without doing anything. Note: calling the run() method directly does not start a new thread, and it is no different from calling a normal Java method.
Therefore, there are two ways to implement your own thread:
Method 1: you can start a new Thread and execute the self-defined run() method by your own class, extend Thread, and copying the run() method. Such as:

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

Start the thread in the right place: new MyThread(). Start ().
Method 2: if your class extends another class, you cannot directly extend the Thread. At this point, you must implement a Runnable interface:

  public class MyThread extends OtherClass implements Runnable {
  public run() {
  System.out.println("MyThread.run()");
  }
  }

To start MyThread, you need to first instantiate a Thread and pass in your own MyThread instance:

  MyThread myt = new MyThread();
  Thread t = new Thread(myt);
  t.start();

In fact, when a Runnable target parameter is passed to the Thread, the Thread's run() method calls target.run(), referring to the JDK source code:

  public void run() {
  if (target != null) {
  target.run();
  }
  }

Related articles: