Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Three ways to implement Java threads


May 30, 2021 Article blog


Table of contents


Inherit the Thread class to create the thread class

Thread's implementation steps:

  1. Define thread's subclasses, override the run() method, the run() method represents the task that the thread wants to complete, and the run() method is called the thread execution body.
  2. Create an instance of the Thread subclass, which is a thread.
  3. Call the start() method of the thread object to start the thread.

public class ThreadDemo extends Thread{

  public void run() {
      for(int i=0;i<10;i++) {
          System.out.println(currentThread().getName()+":" + i);
      }
  }

  public static void main(String args[]) {
      new ThreadDemo().start();
      new ThreadDemo().start();
  }
}

Results:
 Three ways to implement Java threads1

Implement the Runnable interface to create a thread class

Runnable's implementation steps:

  1. Define the Runable interface implementation class, override the run() method, which represents the task that the thread wants to accomplish, and the run() method is called the thread execution body.
  2. Creating an instance of the Runnable implementation class, Runnable itself is a method of the Thread class, so the creation thread also implements a Thread class to wrap the Runnable object.
  3. Call the start() method of the thread object to start the thread.

public class RunnableDemo implements Runnable{

  String threadName;

  public RunnableDemo(String threadName) {
      this.threadName = threadName;
  }

  @Override
  public void run() {
      for(int i=0;i<10;i++) {
          System.out.println(threadName+":" + i);
      }
  }

  public static void main(String args[]) {
      new Thread(new RunnableDemo("A")).start();
      new Thread(new RunnableDemo("B")).start();
  }
}

Results:
 Three ways to implement Java threads2

Implement the Callable interface to create a thread class

The Callable interface has been available since Java5, which is an enhanced version of the Runable interface, which provides a call() method as the thread executor, the call() method can have a return value, and the call() method can declare throwing an exception.

  • boolean cancel(boolean may) attempted to cancel the callable task associated with the Future.
  • V get() returns the return value of the call() method in the Call task. Calling the method becomes a thread block and you must wait until the child thread ends before you get the return value.
  • V get(long timeout,TimeUnit unit) returns the return value of the call() method in the Call task. This method allows the program to block up to the timeout and unit specified time, and if the specified time is passed, if the specified time still does not return a value, the TimeoutException exception is thrown.
  • boolean isCancelled() true if the Callable task is canceled before it completes properly.
  • boolean isDone() returns true if the Callable task is completed.

Runnable's implementation steps:

  1. Create an implementation class for the Callable interface and implement the call() method, which acts as the executor of the thread, and the call() method has a return value.
  2. Wrap the Callable object with the FutrueTask class.
  3. Create and start a new thread using the FutrueTask object as target of the Thread object.
  4. Enable the get() method of the FutrueTask object to get the return value of the child thread.

public class CallableDemo implements Callable<Integer> {
  public static void main(String args[]) {
      FutureTask<Integer> futureTask = new FutureTask<Integer>(new CallableDemo());
      new Thread(futureTask).start();
      try {
          System.out.println("子线程返回值:" + futureTask.get());
      } catch (InterruptedException e) {
          e.printStackTrace();
      } catch (ExecutionException e) {
          e.printStackTrace();
      }
      if (futureTask.isDone()) {
          System.out.println("线程结束");
      }
  }

  @Override
  public Integer call() throws Exception {
      System.out.println("线程开始");
      int ss = 0;
      for (int i = 0; i < 20; i++) {
          ss += i;
      }
      return ss;
  }
}

Results:

 Three ways to implement Java threads3