创建线程的几种方式

创建线程有四种方式:

1、继承Thread类
2、实现Runnable接口
3、Callable和FutureTask
4、线程池

1、继承Thread类

public class MyThread extends Thread {
   public void run() {
      System.out.println(Thread.currentThread().getName() + "在运行!");
   }
}

public static void main(String[] args) {
    MyThread myThread = new MyThread();
    myThread.start();
    System.out.println("主线程在运行!");
}

结果
主线程在运行!
Thread-0在运行!

2、实现Runnable接口

public class MyThread implements Runnable {
   public void run() {
      System.out.println(Thread.currentThread().getName() + "在运行!");
   }
}

public static void main(String[] args) {
    MyThread myThread = new MyThread();
    Thread thread = new Thread(myThread);
    thread.start();
    System.out.println("主线程在运行!");
}
结果
主线程在运行!
Thread-0在运行!

3、Callable和FutureTask

public class MyThread implements Callable<String> {
   @Override
   public String call() {
      System.out.println(Thread.currentThread().getName() + "在运行!");
      return "call执行";
   }
}

public static void main(String[] args) {
    MyThread myThread = new MyThread();
    FutureTask<String> task = new FutureTask<>(myThread);
    Thread thread = new Thread(task);
    thread.start();
    System.out.println("主线程在运行!");
    try {
        String result = task.get();
        System.out.println("子线程返回的结果是:" + result);
    } catch (ExecutionException | InterruptedException e) {
        e.printStackTrace();
    }
}

结果
主线程在运行!
Thread-0在运行!
子线程返回的结果是:call执行

4、线程池

public static void main(String[] args) {
    ExecutorService threadPool = Executors.newFixedThreadPool(1);
    Runnable task = () -> System.out.println(Thread.currentThread().getName() + "在运行!");
    threadPool.submit(task);
    System.out.println("主线程在运行!");
    threadPool.shutdown();
}

可用性排序:

线程池 > Callable和FutureTask > 实现Runnable接口 > 继承Thread类
1、java是单继承的、如果继承Thread则无法继承其他的类,所以实现runnable接口要优于继承Thread的方式。
2、FutureTask本质上和实现Runnable接口一样,但是FutureTask可以通过get方法获取到返回值,所以要优于直接实现Runnable接口的。
3、线程池是最优的。
3.1、其他几种方式创建的线程数量不可控,极易造成线程大量存在,从而引起内存溢出,导致系统崩溃。
3.2、其他几种方式频繁的创建、销毁线程、非常浪费资源。

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值