Briefly understand the four ways of multithreading in Java

The first method is to inherit the Thread class and then rewrite the run method and then call the start method. Because Java implements multiple implementations with single inheritance, it is not recommended to use this method. The code is as follows:

public class Demo extends Thread{

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

  @Override
  public void run() {
    System.out.println("继承Thread类实现多线程");
  }
}

The second method is to implement the Runnable interface. This method is used more. The code is as follows:

public class Demo2 implements Runnable{

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

  @Override
  public void run() {
    System.out.println("实现Runnable接口的多线程");
  }
}

The third method is to implement the Callable interface. The run method of this method has a return value. The code is as follows:

public class Demo3 implements Callable {

  public static void main(String[] args) throws ExecutionException, InterruptedException {
    FutureTask task=new FutureTask(new Demo3());
    new Thread(task).start();
    System.out.println(task.get());
  }

  @Override
  public String call() throws Exception {
    return "实现Callable接口的多线程";
  }
}

The fourth method is to use the thread pool, the code is as follows:

public class Demo4 {

  public static void main(String[] args) {
    ExecutorService executorService= Executors.newCachedThreadPool();
    executorService.execute(new Runnable() {
      @Override
      public void run() {
        System.out.println("线程池实现多线程");
      }
    });
    
    executorService.shutdown();
  }
}

From the above we can see that the thread calls are all using the start() method, so calling the run() method directly can actually output the result, but there is an essential difference, because calling the start() method will increase the number of current threads Increase, and simply calling the run() method is not possible. The start() method actually includes the call to the run() method.

Some high-frequency interview questions collected in the latest 2020 (all organized into documents), there are many dry goods, including mysql, netty, spring, thread, spring cloud, jvm, source code, algorithm and other detailed explanations, as well as detailed learning plans, interviews Question sorting, etc. For those who need to obtain these contents, please add Q like: 11604713672

Guess you like

Origin blog.csdn.net/weixin_51495453/article/details/113866201