线程8大核心基础(一)之实现多线程的方式

这是我参与新手入门的第2篇文章

多线程

多线程的重要性,不需要过多的阐述,日常的业务使用,特别是面试官会给予深厚的关照,如果说对于多线程不是过多熟悉的话,相信会在面试中收到深厚的羞辱…

微信图片_20210707232431.jpg

创建方式

关于多线程的创建方式,网上的文档五花八门,各有各的说法,有2、4、6种等等;到底有多少种呢,关于这个的解答,Oracle的官方文档中早已给出了答复。官方网档链接

There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread

  • 方法一:实现Runnable接口

    /**
     * Runnable方式实现多线程
     */
    public class RunnableStyle implements Runnable{
        @Override
        public void run() {
            System.out.println("实现了Runable方法");
        }
    
        public static void main(String[] args) {
            Thread thread = new Thread(new RunnableStyle());
            thread.run();
        }
    }
    复制代码
  • 方法二:继承Thread类

    public class ThreadStyle extends Thread{
    
        @Override
        public void run() {
            System.out.println("继承Thread类实现多线程");
        }
    
        public static void main(String[] args) {
            new ThreadStyle().start();
        }
    }
    复制代码

实现优劣

方法一(实现Runnable接口)更好

  1. 从代码架构考虑,run方法对应一个具体的任务,应该与线程的创建与运行等线程机制(即Thread类)解耦,从解耦性考虑

  2. 资源节约,每次一个新的任务都需要新建一个独立的线程(继承Thread类),用实现Runnable方法可以利用线程池等机制

  3. 用继承Thread类,因为Java不支持多继承,所以该线程无法继承其他类,对业务上比较麻烦

  4. 源码角度,实现Runnable有一个判断,调用传入的Run方法;继承Thread类的话,是重写了整个Run方法(见上述源码)

        @Override
        public void run() {
            if (target != null) {
                target.run();
            }
        }
    复制代码

总结

  1. 希望大家早日暴富冲冲冲!!!
  2. 个人觉得,原理性的东西,面向源码学习会比直接看博客来得一针见血(轻喷)
  3. 本方法仅代表个人看法,广泛采纳各位看官意见,多多益善嘻嘻嘻~
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享