Java多线程:几种常见的线程创建方法在源码级别的比较

本文详细介绍了Java中创建线程的三种方式:继承Thread类、实现Runnable接口和实现Callable接口。通过源码分析,解释了线程启动过程,以及每种方式的特点和适用场景。继承Thread类操作简单但限制继承,实现Runnable更专注于业务逻辑,而Callable能提供异步返回结果。
摘要由CSDN通过智能技术生成

进行java多线程编码,大多数人首先接触的是线程Thread的创建。常见的线程创建方法有四种,分别是继承Thread类,实现Runnable接口,实现Callable接口以及使用线程池。本篇文章主要讲述前面三种方法,并进行核心源码的比较。

一、继承Thread类

这种方式只需继承Thread,并覆盖其run方法即可,调用对象的start方法即可完成线程的启动和运行。

package multithread.createthread;

public class ThreadExtends extends Thread{
    public ThreadExtends(){
        System.out.println("ThreadExtends构造方法线程名称:"+Thread.currentThread().getName());
    }

    //1、继承Thread类,重写run方法
    public void run() {
        System.out.println("运行ExtendsThread.run(),线程名称:"+Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        new ThreadExtends().start();
    }

}
ThreadExtends构造方法线程名称::main
运行ExtendsThread.run(),线程名称:Thread-0

1、start方法的作用

从运行结果来看到一个现象:ThreadExtends构造方法中打印到当前的线程还是main,到了run方法时才是Thread-0。这个是为什么呢?

这是因为main方法是一个线程,程序在main方法体内运行,在未调用ThreadExtends的start前,还是只有一个线程main。当调用start方法后,即可创新新线程Thread-0。因此出现上述情况。既然如此我们看下Thread的源码,深入了解整个创建流程。

2、Thread相关源码解读

   Thread 实现了Runnable接口,而实现Runnable接口也是创建线程的一种方式(其只有一个run接口)。只是继承Thread编程来说相对简单,不足之处就是无法再继承其他类了。

class Thread implements Runnable {

因为我们调用无参的构造方法进行对象创建,我们就定位到这个方法上。这里也解答了我一个疑问,为什么新建的线程的名称都是“Thread-*”(本例的新建线程名称为Thread-0)。nextThreadNum()是获取当前线程初始化序号,这个序号初始是0,每次调用nextThreadNum方法返回当前值,并进行+1操作。


    /* For autonumbering anonymous threads. */
    private static int threadInitNumber;
    private static synchronized int nextThreadNum() {
        return threadInitNumber++;
    }

    /**
     * Allocates a new {@code Thread} object. This constructor has the same
     * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
     * {@code (null, null, gname)}, where {@code gname} is a newly generated
     * name. Automatically generated names are of the form
     * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
     */
    public Thread() {
        init(null, null, "Thread-" + nextThreadNum(), 0);
    }


    /**
     * Initializes a Thread with the current AccessControlContext.
     * @see #init(ThreadGroup,Runnable,String,long,AccessControlContext)
     */
    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize) {
        init(g, target, name, stackSize, null);
    }

    /**
     * Initializes a Thread.
     *
     * @param g the Thread group
     * @param target the object whose run() method gets called
     * @param name the name of the new Thread
     * @param stackSize the desired stack size for the new thread, or
     *        zero to indicate that this parameter is to be ignored.
     * @param acc the AccessControlContext to inherit, or
     *            AccessController.getContext() if null
     */
    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc) {
        if (name == null) {
            throw new NullPointerException("name cannot be null");
        }

        this.name = name.toCharArray();

        Thread parent = currentThread();
        SecurityManager security = System.getSecurityManager();
        if (g == null) {
            /* Determine if it's an applet or not */

            /* If there is a security manager, ask the security manager
               what to do. */
            if (security != null) {
                g = security.getThreadGroup();
            }

            /* If the security doesn't have a strong opinion of the matter
               use the parent thread group. */
            if (g == null) {
                g = parent.getThreadGroup();
            }
        }

        /* checkAccess regardless of whether or not threadgroup is
           explicitly passed in. */
        g.checkAccess();

        /*
         * Do we have the required permissions?
         */
        if (security != null) {
            if (isCCLOverridden(getClass())) {
                security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
            }
        }

        g.addUnstarted();

        this.group = g;
        this.daemon = parent.isDaemon();
        this.priority = parent.getPriority();
        if (security == null || isCCLOverridden(parent.getClass()))
            this.contextClassLoader = parent.getContextClassLoader();
        else
            this.contextClassLoader = parent.contextClassLoader;
        this.inheritedAccessControlContext =
                acc != null ? acc : AccessController.getContext();
        this.target = target;
        setPriority(priority);
        if (parent.inheritableThreadLocals != null)
            this.inheritableThreadLocals =
                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
        /* Stash the specified stack size in case the VM cares */
        this.stackSize = stackSize;

        /* Set thread ID */
        tid = nextThreadID();
    }

接下来我们进行跟踪init方法。当中参数AccessControlContext,用于根据其封装的上下文做出系统资源访问决策,本例中没传入值,默认为null。参数stackSize,该参数指定了JVM分配线程栈的地址空间的字节数,如果为0则指不起作用。

        Thread parent = currentThread();
        SecurityManager security = System.getSecurityManager();
        if (g == null) {
            /* Determine if it's an applet or not */

            /* If there is a security manager, ask the security manager
               what to do. */
            if (security != null) {
                g = security.getThreadGroup();
            }

            /* If the security doesn't have a strong opinion of the matter
               use the parent thread group. */
            if (g == null) {
                g = parent.getThreadGroup();
            }
        }

这里我们可以看到有一行代码:“Thread parent = currentThread();”。此阶段该线程在处于创建阶段,状态值为NEW,父线程就是创建自身线程的那个线程,也就是main 。也许有人会问,main线程又是谁创建的?答案是JVM。

安全管理器SecurityManager并不存在,因此线程组属性g的引用指向父线程线程组。

接下来看以下三行代码:

        this.group = g;
        this.daemon = parent.isDaemon();
        this.priority = parent.getPriority();

我们可以知道三个信息:1、当前线程的线程组指向父线程的线程组对象;2、线程的类别与父线程一致(线程分为守护线程(daemon)和非守护线程);3、线程的优先级与父线程一致。

二、实现Runnable接口

这种方式只需实现Runnable,并实现该接口类中的run抽象方法即可,把自己作为参数传递到Thread中去,调用对象的start方法即可完成线程的启动和运行。

这种方法写法比继承Thread方式要麻烦一点,但是如官方所说,实现Runnable方式可以只考虑run方法处理业务,除非需要修改或者增强类的基本行为,不然都不建议使用继承Thread方式来创建线程。

package multithread.createthread;

public class RunnableImpl implements Runnable{
    @Override
    public void run() {
         System.out.println("RunnableImpl.run(),线程名称:"+Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        new Thread(new RunnableImpl()).start();
    }
}
RunnableImpl.run(),线程名称:Thread-0

接下来我们看下Runnable的源码。官方描述:启动线程会导致在单独执行的线程中调用对象的run方法,本例中的start方法调用后,会连带调用run方法。另外,我们可以在run方法中写入我们任务。

public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

三、实现Callable接口

这种方式只需实现Callable,并实现该接口类中的call抽象方法,间接地把自己作为参数传递到Thread中去,调用对象的start方法即可完成线程的启动和运行。

1、实现步骤

这种方法相比Runnable方式更为繁琐一些,但是却可以得到异步返回值。一般需要以下四步操作:

1、实现类,要实现Callable中的call方法

2、实例一个FutureTask对象,把实现类实例作为参数传给FutureTask对象

3、实力一个Thread对象,并把FutureTask对象传给该对象

4、通过调用FutureTask对象的get方法获取返回结果

package multithread.createthread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class CallableImpl  implements Callable {
    @Override
    public Object call() throws Exception {
        System.out.println("运行 CallableImpl.call(),"+Thread.currentThread().getName());
        return "CallableImpl返回信息";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask ft = new FutureTask<>(new CallableImpl());
        new Thread(ft).start();
        String callback = (String) ft.get();
        System.out.println(callback);
    }
}
运行 CallableImpl.call(),Thread-0
CallableImpl返回信息

从FutureTask可以作为Thread的构造方法参数来看,FutureTask必是与Runnable有关联。接下来我们直接从源码上找到答案。

2、Callable、FutureTask等源码分析

Callable在jdk1.5出现,call方法可返回结果,不过也需要我们对异常进行处理。

/**
 * A task that returns a result and may throw an exception.
 * Implementors define a single method with no arguments called
 * {@code call}.
 *
 * <p>The {@code Callable} interface is similar to {@link
 * java.lang.Runnable}, in that both are designed for classes whose
 * instances are potentially executed by another thread.  A
 * {@code Runnable}, however, does not return a result and cannot
 * throw a checked exception.
 *
 * <p>The {@link Executors} class contains utility methods to
 * convert from other common forms to {@code Callable} classes.
 *
 * @see Executor
 * @since 1.5
 * @author Doug Lea
 * @param <V> the result type of method {@code call}
 */
@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

FutureTask类中,我们看到其实现RunnableFuture接口,不过并不是我们所要的Runnable。

public class FutureTask<V> implements RunnableFuture<V> {

我们继续对RunnableFuture进行跟踪,发现这个接口是继承了Runnable和Future这两个接口。也许有人会像我刚开始接触时的惊讶,Java不是单继承的吗?

java类对父类是单继承,接口是可以继承多个父接口的。

Future表示异步计算的结果只要这个run方法的成功执行,那么Future就完成,并允许访问其结果

public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}
回到FutureTask,在构造方法中确保callable完成初始化。

public FutureTask(Callable<V> callable) {
    if (callable == null)
        throw new NullPointerException();
    this.callable = callable;
    this.state = NEW;       // ensure visibility of callable
}

四、总结

以上三种创建线程的的方式,其实是相互联系。都需要用到Thread这个类,并调用Thread的start方法,才能新建线程。

继承Thread类的方式,操作简单,但是因为其继承了Thread后,就限制了再继承其他类的可能性。

实现Runnable的方式,操作较复杂,不过其只关注run方法,在不需要增强类其他方法的前提下,官方更推荐这种方式。

实现Callable的方式,操作是三种中最复杂的,但是其提供异步返回结果,对于一些需要计算结果的场景来说是非常友好的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值