JAVA启动线程的五种方式

1、new Thread().start();
2、 new Thread(Runnable).start()
3、lambda表达式
4、Executors.newCachedThreadPool()
5、FutureTask + Callable

代码来啦

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";
      }
  }


}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页