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. 实现接口后还可以继承其他的类和实现其他的接口,可扩展性更好。
发布了258 篇原创文章 · 获赞 161 · 访问量 32万+

猜你喜欢

转载自blog.csdn.net/qq_37960603/article/details/103922663