Five ways to start threads in JAVA

1、new Thread().start();
2、 new Thread(Runnable).start()
3、线程池
4、Executors.newCachedThreadPool()
5、FutureTask + Callable

The code is coming

package com.changsheng;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
* @author 
*/
public class ThreadStartMode {
    
    
   
   //启动线程的5种方式
   public static void main(String[] args) {
    
    
       //1、thread
       new MyThread().start();
       //2、runnable
       new Thread(new MyRun()).start();
       //线程池实质上也是用的这两种之一。
       //3、lambda
       new Thread(()-> System.out.println("Hello Lambda!")).start();
       //4、FutureTask + Callable
       Thread t = new Thread(new FutureTask<String>(new MyCall()));
       t.start();
       //5、Executors.newCachedThreadPool()
       ExecutorService service = Executors.newCachedThreadPool();
       service.execute(()->{
    
    
           System.out.println("Hello ThreadPool");
      });
       service.shutdown();
  }

static class MyThread extends Thread {
    
    
       @Override
       public void run() {
    
    
           System.out.println("Hello MyThread!");
      }
  }

   static class MyRun implements Runnable {
    
    
       @Override
       public void run() {
    
    
           System.out.println("Hello MyRun!");
      }
  }

   static class MyCall implements Callable<String> {
    
    
       @Override
       public String call() {
    
    
           System.out.println("Hello MyCall");
           return "success";
      }
  }


}

Guess you like

Origin blog.csdn.net/qq_38095257/article/details/113108439