【Java】Java多线程基础之OOP源码剖析

一、OOP之Thread、Runnable和Callable

        Java中Thread代表线程对象,而Runnable和Callable均代表了线程执行的target对象,这种设计透露了OOP的思想,在AOP思想盛行的今天,再回顾一下OOP设计的精妙!

        常常说Java创建线程有三种方式,分别是Thread、Runnable、Callable三种。换个角度来看实际上就一种Thread,最终都是new出来一个Thread对象,通过start方法调用线程执行体run方法。Thread里面本来就有线程执行体run方法,但是如果你传入了新的target(Runnable或者Callable),那么就在自己的线程执行体run中转调target的run方法作为线程执行体。

        简单总结一下,再从节选的源码中剖析。

        创建线程的方式之OOP思想:

        1. 如果是采用继承Thread的方式创建线程,则需要重写run的逻辑,通过OOP中多态的思想(父类引用直接指向子类对象)或者理解成动态加载技术实际上调用的是子类的线程执行体run;

        2. 如果采用的是传入target(传入Runnable或Callable)方式创建线程,则调用的还是Thread对象中的原生的run方法,该run中则转调target的run方法来完成线程的执行;

        3. 实际上,线程执行体不是taret中的run方法,而是Thread中的run方法;

        如果需要简单了解三种方式的创建过程,烦请参见另一篇博客:《多线程基础》,写的比较早,比较粗浅,见谅!


二、OOP之源码剖析

        下面,进入源码剖析。

1. Thread

/**
 * Causes this thread to begin execution; the Java Virtual Machine
 * calls the <code>run</code> method of this thread.
 * <p>
 * The result is that two threads are running concurrently: the
 * current thread (which returns from the call to the
 * <code>start</code> method) and the other thread (which executes its
 * <code>run</code> method).
 * <p>
 * It is never legal to start a thread more than once.
 * In particular, a thread may not be restarted once it has completed
 * execution.
 *
 * @exception  IllegalThreadStateException  if the thread was already
 *               started.
 * @see        #run()
 * @see        #stop()
 * 正确启动线程的方法,该方法做了两件事
 * 	1. 启动本地线程
 *	2. 在本地线程中转调线程执行体run方法
 */
public synchronized void start() {
	/**
	 * This method is not invoked for the main method thread or "system"
	 * group threads created/set up by the VM. Any new functionality added
	 * to this method in the future may have to also be added to the VM.
	 *
	 * A zero status value corresponds to state "NEW".
	 */
	if (threadStatus != 0)
		throw new IllegalThreadStateException();

	/* Notify the group that this thread is about to be started
	 * so that it can be added to the group's list of threads
	 * and the group's unstarted count can be decremented. */
	group.add(this);

	boolean started = false;
	try {
		//启动本地线程的方法
		start0();
		started = true;
	} finally {
		try {
			if (!started) {
				group.threadStartFailed(this);
			}
		} catch (Throwable ignore) {
			/* do nothing. If start0 threw a Throwable then
			  it will be passed up the call stack */
		}
	}
}
//native方法,用于启动操作系统中的真正线程
private native void start0();

/**
 * If this thread was constructed using a separate
 * <code>Runnable</code> run object, then that
 * <code>Runnable</code> object's <code>run</code> method is called;
 * otherwise, this method does nothing and returns.
 * <p>
 * Subclasses of <code>Thread</code> should override this method.
 *
 * @see     #start()
 * @see     #stop()
 * @see     #Thread(ThreadGroup, Runnable, String)
 * 线程执行体
 *	1. 如果采用继承方式来实现线程,那么因为多态,则不会调用该方法,而是调用子类的run方法
 *	2. 如果采用target方式来实现线程,那么直接调用该方法,但是在该方法中转调了target的run方法,实际上我们自己组织的逻辑在
 *		target的run方法中
 */
@Override
public void run() {
	if (target != null) {
		target.run();
	}
}

/**
 * This method is called by the system to give a Thread
 * a chance to clean up before it actually exits.
 * 线程推出前的资源回收操作
 */
private void exit() {
	if (group != null) {
		group.threadTerminated(this);
		group = null;
	}
	/* Aggressively null out all reference fields: see bug 4006245 */
	target = null;
	/* Speed the release of some of these resources */
	threadLocals = null;
	inheritableThreadLocals = null;
	inheritedAccessControlContext = null;
	blocker = null;
	uncaughtExceptionHandler = null;
}

2. Runnable

        首先不要忘了,Runnable是作为线程执行的target而存在,看一下Thread中有关target的源码如下。

/*
 * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * @author  unascribed
 * @see     Runnable
 * @see     Runtime#exit(int)
 * @see     #run()
 * @see     #stop()
 * @since   JDK1.0
 */
public class Thread implements Runnable {
	/* What will be run. */
	//线程中明确定义了target作为其属性,默认值为null
    private Runnable target;
	
	/**
     * Allocates a new {@code Thread} object. This constructor has the same
     * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
     * {@code (null, target, 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.
     *
     * @param  target
     *         the object whose {@code run} method is invoked when this thread
     *         is started. If {@code null}, this classes {@code run} method does
     *         nothing.
	 * 如果构造方法中传入target,则在init方法中将传入的target赋给自己的属性target,否则传入自己的属性target值为null
     */
    public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }
	
	/**
     * Allocates a new {@code Thread} object. This constructor has the same
     * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
     * {@code (null, target, name)}.
     *
     * @param  target
     *         the object whose {@code run} method is invoked when this thread
     *         is started. If {@code null}, this thread's run method is invoked.
     *
     * @param  name
     *         the name of the new thread
	 * 同上,只是线程自定义名称
     */
    public Thread(Runnable target, String name) {
        init(null, target, name, 0);
    }
	
	/**
     * 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();
		//在此处完成target的注入
        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();
    }
	
	/**
     * If this thread was constructed using a separate
     * <code>Runnable</code> run object, then that
     * <code>Runnable</code> object's <code>run</code> method is called;
     * otherwise, this method does nothing and returns.
     * <p>
     * Subclasses of <code>Thread</code> should override this method.
     *
     * @see     #start()
     * @see     #stop()
     * @see     #Thread(ThreadGroup, Runnable, String)
	 * 重点方法,在没有多态的前提下(非继承Thread方式创建线程),是调用该方法
	 * 但是在该方法中,转调了传进来的Runnable的run方法
	 * 也即是实际上在线程执行体中实际运行的是该run方法,但是run方法转调了我们自己写的逻辑——Runnable中的run方法
     */
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }
}

        在Thread中成功完成方法的转调,转调到了Runnable的run方法,实际上Runnable是一个接口,该接口里面就一个方法run的声明,而采用Runnable方式创建线程,是需要我们实现Runnable接口并重写线程执行逻辑run方法。Runnable源码如下。

/*
 * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package java.lang;

/**
 * The <code>Runnable</code> interface should be implemented by any
 * class whose instances are intended to be executed by a thread. The
 * class must define a method of no arguments called <code>run</code>.
 * <p>
 * This interface is designed to provide a common protocol for objects that
 * wish to execute code while they are active. For example,
 * <code>Runnable</code> is implemented by class <code>Thread</code>.
 * Being active simply means that a thread has been started and has not
 * yet been stopped.
 * <p>
 * In addition, <code>Runnable</code> provides the means for a class to be
 * active while not subclassing <code>Thread</code>. A class that implements
 * <code>Runnable</code> can run without subclassing <code>Thread</code>
 * by instantiating a <code>Thread</code> instance and passing itself in
 * as the target.  In most cases, the <code>Runnable</code> interface should
 * be used if you are only planning to override the <code>run()</code>
 * method and no other <code>Thread</code> methods.
 * This is important because classes should not be subclassed
 * unless the programmer intends on modifying or enhancing the fundamental
 * behavior of the class.
 *
 * @author  Arthur van Hoff
 * @see     java.lang.Thread
 * @see     java.util.concurrent.Callable
 * @since   JDK1.0
 */
@FunctionalInterface
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();
}


3. Callable

        无论是通过继承Thread还是通过实现Runnable来创建线程,都无法获取线程是否执行完成的状态,也就是作为线程执行体的run方法并没有返回值,因此在JDK 1.5中增加了Callable方式创建线程,该方式允许执行的线程抛出异常和返回执行的状态(返回值)。看一下Callable的代码。

/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent;

/**
 * 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;
}
        Callable作为一个接口和Runnable差不多,要想通过该方式来创建线程,也需要我们自己实现该接口,重写call方法,实际上我们创建线程的执行逻辑也在该方法中。

        现在存在的疑问是:本地线程怎么调用call方法来执行我们的逻辑?

        在Java已有的线程逻辑中,要想本地线程调用该方法,Callable要么继承Thread,要么继承Runnable,显然接口不可能继承Thread,那么就剩下继承Runnable一条路,但是Callable接口并没有继承任接口,这是为什么呢?已经明确的是,真正的线程执行体是Thread类或其子类中的run方法,而不是其他任何类中的run方法,那么无论如何通过Thread或Runnable是无法获取返回值的。为了实现获取返回值,Callable的实现类需要被封装到FutureTask对象中,因此FutureTask必然实现Runnable或继承Thread,无论采用哪一种方式,实现或重写run方法都不会有返回值,因此需要通过在FutureTask中定义属性保存执行结果,从而返回。事实上,要想获取返回值,FutureTask继承Thread可以做到,实现Runnable接口也可以做到,Java为了更好的扩展性,采用了实现Runnable接口,相关源码摘取如下所示。

/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent;
import java.util.concurrent.locks.LockSupport;

/**
 * A cancellable asynchronous computation.  This class provides a base
 * implementation of {@link Future}, with methods to start and cancel
 * a computation, query to see if the computation is complete, and
 * retrieve the result of the computation.  The result can only be
 * retrieved when the computation has completed; the {@code get}
 * methods will block if the computation has not yet completed.  Once
 * the computation has completed, the computation cannot be restarted
 * or cancelled (unless the computation is invoked using
 * {@link #runAndReset}).
 *
 * <p>A {@code FutureTask} can be used to wrap a {@link Callable} or
 * {@link Runnable} object.  Because {@code FutureTask} implements
 * {@code Runnable}, a {@code FutureTask} can be submitted to an
 * {@link Executor} for execution.
 *
 * <p>In addition to serving as a standalone class, this class provides
 * {@code protected} functionality that may be useful when creating
 * customized task classes.
 *
 * @since 1.5
 * @author Doug Lea
 * @param <V> The result type returned by this FutureTask's {@code get} methods
 */
public class FutureTask<V> implements RunnableFuture<V> {
    /** The underlying callable; nulled out after running */
	//和Thread中private Runnable target如出一辙,都是为了线程逻辑的注入
    private Callable<V> callable;
	/** The result to return or exception to throw from get() */
	//run的返回值是void,因此要想获取返回值,就只能保存到FutureTask的属性中,outcome因此而生
    private Object outcome; // non-volatile, protected by state reads/writes
	
	/**
     * Creates a {@code FutureTask} that will, upon running, execute the
     * given {@code Callable}.
     *
     * @param  callable the callable task
     * @throws NullPointerException if the callable is null
	 * FutureTask的所有两个构造方法都需要注入参数
	 * 1. 如果返回值是需要根据线程执行而产生变化,则采用该构造法方法
	 * 2. 如果返回值不需要根据线程的执行而变化,在执行前就能确定,那么就应该调用FutureTask(Runnable runnable, V result)方法
	 * 
     */
    public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

    /**
     * Creates a {@code FutureTask} that will, upon running, execute the
     * given {@code Runnable}, and arrange that {@code get} will return the
     * given result on successful completion.
     *
     * @param runnable the runnable task
     * @param result the result to return on successful completion. If
     * you don't need a particular result, consider using
     * constructions of the form:
     * {@code Future<?> f = new FutureTask<Void>(runnable, null)}
     * @throws NullPointerException if the runnable is null
	 * FutureTask的两个构造方法之一,采用该构造方法,需要提前明确返回值,即返回值不应该随着线程的执行而变化,提前就可以确定
	 * 传入的Runnable在Executors中通过静态内部类 RunnableAdapter<T> implements Callable<T>进行改写,最终也转成了Callable
     */
    public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }
	
	/**
	 * FutureTask实现了Runnable,因此需要重写run方法
	 * 1. run方法中转调了Callable的call方法
	 * 2. call方法执行的返回值通过set方法保存到了属性outcome中
	 * 3. 要想获得返回值,则需要调用FutureTask的get方法,获取outcome属性的值
	 */
	public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
					//转调Callable,并获取返回值
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
				//如果执行成功,则将返回值赋值给实例属性outcome
                if (ran)
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }
	
	/**
     * Sets the result of this future to the given value unless
     * this future has already been set or has been cancelled.
     *
     * <p>This method is invoked internally by the {@link #run} method
     * upon successful completion of the computation.
     *
     * @param v the value
	 * 将Callable中call方法执行的返回值赋给outcome属性
     */
    protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();
        }
    }
	
	/**
     * @throws CancellationException {@inheritDoc}
	 * 获取线程执行的返回值,实际上获取的是我们自定义线程执行逻辑的返回值,而不是线程执行体的返回值
	 * 线程执行体是永远没有返回值的,Java采用了一种这种的方法来实现
     */
    public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }
}
        至此,多线程中OOP的思想剖析结束。


附注:

        本文如有错漏,烦请不吝指正,谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值