【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 thenit 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方法中 */@Overridepublic 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 * @seeRunnable * @seeRuntime#exit(int) * @see#run() * @see#stop() * @since JDK1.0 */public class Thread implements Runnable {/* What will be run. *///线程中明确定义了target作为其属性,默认值为nullprivate 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 managerwhat to do. */if (security != null) {g = security.getThreadGroup();}/* If the security doesn't have a strong opinion of the matteruse the parent thread group. */if (g == null) {g = parent.getThreadGroup();}}/* checkAccess regardless of whether or not threadgroup isexplicitly 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();elsethis.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方法*/@Overridepublic void run() {if (target != null) {target.run();}}}一定要记得挺身而出,即便帮不了忙,安慰也是最大的支持.

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

相关文章:

你感兴趣的文章:

标签云: