Java实现多线程到底有多少种方法?

推荐:Java并发编程汇总

Java实现多线程到底有多少种方法?

可以去百度一下,会有很多不同的答案。
在这里插入图片描述
到底有多少种呢?这就要去官方文档一探究竟了。
Java™ Platform, Standard Edition 8 API Specification
lang包下Thread类的说明中可以看到下面这段英文。

There are two ways to create a new thread of execution.

可以看到官方给出了说法,有两种实现多线程的方法。
到底是哪两种呢?

1 继承Thread类

One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and started.

上面英文来自官方文档,也就是说继承Thread类,重写run()方法。

// 用 Thread 方法实现多线程
public class ThreadStyle extends Thread{

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

    @Override
    public void run() {
        System.out.println("用 Thread 方法实现多线程!");
    }
}

2 实现Runnable接口

The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started.

上面英文来自官方文档,也就是说实现Runnable接口,实现run()方法。

// 用 Runnable 方法实现多线程
public class RunnableStyle implements Runnable {

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

    @Override
    public void run() {
        System.out.println("用 Runnable 方法实现多线程!");
    }
}

3 为什么会有这么多说法

官方给出两种实现多线程的方法,为什么会有这么多不同的答案?
这些答案其实也有一定的道理,那些方法也可以实现多线程,但其底层终究还是使用了上面两种方法。

4 哪种方法更好呢

实现Runnable接口这种方法更好。
这种方法有以下优点:

  1. 从代码架构角度考虑,这种方法可以将线程具体执行的任务和线程的创建、运行机制等进行解耦。
  2. 可以利用线程池工具,大大减少创建线程、销毁线程等的消耗,更方便资源的节约。
  3. 实现接口后还可以继承其他的类和实现其他的接口,可扩展性更好。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ITKaven

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值