Java并发编程之线程创建

  • Java线程的实现方式
  • Thread创建线程
  • Thread类继承创建线程
  • Runnable接口方式
  • Lambda 表达式Runnable接口方式
  • 线程的启动
  • Thread源码解析
  • Runnable源码解析
  • ThreadGroup源码解析


Java线程的实现方式

Java中进行线程创建的方式,个人习惯问题会有几种形式。方式有如下几种:1.thread创建线程 2.创建一个类继承Thread类 3.实现Runnable接口实现 4.使用lambda表达式的方式创建

Thread创建线程

在java中创建线程,使用java.lang.Thread类进行创建。实例如下

Thread thread = new Thread();

以上代码是创建一个线程

Thread类继承创建线程

使用继承的方式进行创建线程如下:
1.创建一个MyThread的类,继承Thread:

class MyThread extends Thread{
	   @Override
	    public void run() {
	        // TODO Auto-generated method stub
	        System.out.println("by extend Thread class, overring run function excu code");
	    }
	}

2.实例化

Thread thread = new MyThread();

重写run方法,是线程执行的逻辑。

Runnable接口方式

使用Runnable接口方式进行创建线程如下:
1.创建一个MyThreadRunnableImpl的类,实现Runnable:

public class MyThreadRunnableImpl implements Runnable{
	@Override
	public void run() {
    	// TODO Auto-generated method stub
    	System.out.println("impl Runnable interface,overring run function to excu code");
	}
}

2.实例化

Thread thread = new Thread(new MyThreadRunnableImpl ());

Lambda 表达式Runnable接口方式

Lambda 表达式Runnable接口方式进行创建线程如下:

Runnable runnable = () -> {
        System.out.println("use lambda impl runnable");
    };

2.实例化

Thread threadLabRun = new Thread(runnable);

线程的启动

线程的启动,使用Thread中的start方法进行启动,如下

thread.start();

可以根据个人喜欢选择使用的创建线程的方式,个人建议使用实现Runnable接口的方式进行创建。
有时你可能必须实现Runnable以及线程的子类。例如,如果创建一个线程的子类,可以执行多个可运行线程。这是实现线程池的典型情况。

Thread源码解析

上面了解了线程的创建方式,现在就看看Thread是如何操作的?
thread的源码如下:

//thread类实现了Runnable接口,使用run方法进行执行相关的逻辑代码
public class Thread implements Runnable {

    /* 确保registerNatives是<clinit>做的第一件事 */
    private static native void registerNatives();
    
    static {
        registerNatives();
    }

    private volatile String name;  //线程名称
    private int            priority;  //线程执行的优先级
    private Thread         threadQ; 
    private long           eetop;
    /* 是否单步执行此线程. */
    private boolean     single_step;
    /* 该线程是否为守护线程. */
    private boolean     daemon = false;
    /* JVM状态 */
    private boolean     stillborn = false;
    /* 要执行什么操作*/
    private Runnable target;
    /* 该线程组 */
    private ThreadGroup group;
    /* 此线程的上下文类加载器 */
    private ClassLoader contextClassLoader;
    /* 此线程继承的AccessControlContext */
    private AccessControlContext inheritedAccessControlContext;
    /*为自动编号匿名线程. */
    private static int threadInitNumber;
    private static synchronized int nextThreadNum() {
        return threadInitNumber++;
    }
/* 属于这个线程的ThreadLocal值。这个映射由ThreadLocal类维护 */
ThreadLocal.ThreadLocalMap threadLocals = null;
/*
 * 属于这个线程的InheritableThreadLocal值。这个映射由InheritableThreadLocal类维护。
 */
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
/*
 此线程请求的堆栈大小,如果创建者没有指定堆栈大小,则为0。VM可以对这个数字做任何它喜欢的事情;有些vm会忽略它。
 */
private long stackSize;
/*
 * 在本机线程终止后持续存在的jvm私有状态
 */
private long nativeParkEventPointer;
/*
 * 线程id
 */
private long tid;
/* 生成threadid */
private static long threadSeqNumber;
/* Java线程工具的状态
 * 初始化,表示线程“尚未启动”
 */
private volatile int threadStatus = 0;
//同步生成线程id
private static synchronized long nextThreadID() {
    return ++threadSeqNumber;
}
volatile Object parkBlocker;
private volatile Interruptible blocker;
private final Object blockerLock = new Object();

/* 设置拦截器字段;通过sun.misc调用
 */
void blockedOn(Interruptible b) {
    synchronized (blockerLock) {
        blocker = b;
    }
}
/**
 * 线程可以拥有的最低优先级
 */
public final static int MIN_PRIORITY = 1;

   /**
     * 分配给线程的默认优先级
     */
    public final static int NORM_PRIORITY = 5;
/**
 * 线程可拥有的最大优先级
 */
public final static int MAX_PRIORITY = 10;
/**
 * 返回当前运行的线程
 */
public static native Thread currentThread();

   //初始化线程
    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize) {
        init(g, target, name, stackSize, null, true);
    }


private void init(ThreadGroup g, Runnable target, String name,
                  long stackSize, AccessControlContext acc,
                  boolean inheritThreadLocals) {
    if (name == null) {
        throw new NullPointerException("name cannot be null");
    }

    this.name = name;

    Thread parent = currentThread();
    SecurityManager security = System.getSecurityManager();
    if (g == null) {
        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 (inheritThreadLocals && 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();
}

/**
 * 构造函数
 */
public Thread() {
    init(null, null, "Thread-" + nextThreadNum(), 0);
}

/**
构造函数  传一个Runnable对象
 */
public Thread(Runnable target) {
    init(null, target, "Thread-" + nextThreadNum(), 0);
}

    /**
   构造函数,传一个Runnable和AccessControlContext上下文
     */
    Thread(Runnable target, AccessControlContext acc) {
        init(null, target, "Thread-" + nextThreadNum(), 0, acc, false);
    }

/**
 构造函数,传一个线程组对象和Runnable对象
 */
public Thread(ThreadGroup group, Runnable target) {
    init(group, target, "Thread-" + nextThreadNum(), 0);
}

/**
 带线程名的线程
 */
public Thread(String name) {
    init(null, null, name, 0);
}

/**
带线程组
 */
public Thread(ThreadGroup group, String name) {
    init(group, null, name, 0);
}

/**
带Runnable接口和线程名
 */
public Thread(Runnable target, String name) {
    init(null, target, name, 0);
}

/**
创建一个线程 当前现场组,Runnable对象和线程名
 */
public Thread(ThreadGroup group, Runnable target, String name) {
    init(group, target, name, 0);
}

/**
创建一个线程 当前现场组,Runnable对象和线程名与线程请求的堆栈大小
 */
public Thread(ThreadGroup group, Runnable target, String name,
              long stackSize) {
    init(group, target, name, stackSize);
}

/**
启动线程 为同步方法
 */
public synchronized void start() {
    /**
     * 此方法不会为主方法线程或“系统”调用
     * 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.
     *
     * 状态值为零对应状态“NEW”
     */
    if (threadStatus != 0)
        throw new IllegalThreadStateException();

    /* 通知线程组当前线程即将启动
     *向线程组添加当前线程
     * and the group's unstarted count can be decremented. */
    group.add(this);
	//当前线程启动标记
    boolean started = false;
    try {
        start0();   //调用native方法进行启动线程
        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 */
        }
    }
}

private native void start0();

/**
 * 如果线程进行实现Runnable接口进行分离逻辑,将执行接口类中的run方法 
 * 如果使用子类的话,子类需要重写run方法,进行相应的逻辑编写,不然线程将不执行任何逻辑
 * /
@Override
public void run() {
    if (target != null) {
        target.run();
    }
}
}

Runnable源码解析

在Thread的源码中可以看出,Thread类实现了Runnable接口,这个接口很简单,只有一个run方法,源码如下:

@FunctionalInterface   //Java 8中的函数式接口申明
public interface Runnable {
    /**
    当一个对象实现了Runnable去创建一个线程,开始线程的时候将执行接口中的run方法,进行相关的逻辑分离
      */
    public abstract void run();
}

ThreadGroup源码解析

在Thread类中,创建的时候可以传入一个ThreadGroup对象,我们看看ThreadGroup对象中执行了哪些操作?管理线程组。

public class ThreadGroup implements Thread.UncaughtExceptionHandler {
    private final ThreadGroup parent;  //线程组所属的父组
    String name; //线程组的名称
    int maxPriority;  //最大的优先级
    boolean destroyed; //是否销毁
    boolean daemon; //是否为守护进程
    boolean vmAllowSuspension; 

    int nUnstartedThreads = 0;  //没有开始的线程个数
    int nthreads; //线程的个数
    Thread threads[];  //线程

    int ngroups; //线程组的
    ThreadGroup groups[];

    /**
     初始化一个空的线程组
     */
    private ThreadGroup() {     // called from C code
        this.name = "system";
        this.maxPriority = Thread.MAX_PRIORITY;
        this.parent = null;
    }

    /**
     初始化一个线程组,执行线程组的名字	     */
    public ThreadGroup(String name) {
        this(Thread.currentThread().getThreadGroup(), name);
    }

    /**
     初始化一个新的线程组,指定父的线程组及其线程组的名字
     */
    public ThreadGroup(ThreadGroup parent, String name) {
        this(checkParentAccess(parent), parent, name);
    }

    private ThreadGroup(Void unused, ThreadGroup parent, String name) {
        this.name = name;
        this.maxPriority = parent.maxPriority;
        this.daemon = parent.daemon;
        this.vmAllowSuspension = parent.vmAllowSuspension;
        this.parent = parent;
        parent.add(this);
    }

    /*
     检测父的线程组
     */
    private static Void checkParentAccess(ThreadGroup parent) {
        parent.checkAccess();
        return null;
    }

    /**
     返回线程组的名字
     */
    public final String getName() {
        return name;
    }

    /**
    返回线程的组的父线程组
     */
    public final ThreadGroup getParent() {
        if (parent != null)
            parent.checkAccess();
        return parent;
    }

    /**
     返回线程组的最大优先级	     */
    public final int getMaxPriority() {
        return maxPriority;
    }

    /**
    返回线程组是否为守护线程组
     */
    public final boolean isDaemon() {
        return daemon;
    }

    /**
     返回线程组是否有销毁	     */
    public synchronized boolean isDestroyed() {
        return destroyed;
    }

    /**
     设置线程组是否为守护线程组
     */
    public final void setDaemon(boolean daemon) {
        checkAccess();
        this.daemon = daemon;
    }

    /**
    设置最大的线程组中最大的优先级
     */
    public final void setMaxPriority(int pri) {
        int ngroupsSnapshot;
        ThreadGroup[] groupsSnapshot;
        synchronized (this) {
            checkAccess();
            if (pri < Thread.MIN_PRIORITY || pri > Thread.MAX_PRIORITY) {
                return;
            }
            maxPriority = (parent != null) ? Math.min(pri, parent.maxPriority) : pri;
            ngroupsSnapshot = ngroups;
            if (groups != null) {
            ·	//进行线程组的复制
                groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
            } else {
                groupsSnapshot = null;
            }
        }
        //进行设置
        for (int i = 0 ; i < ngroupsSnapshot ; i++) {
            groupsSnapshot[i].setMaxPriority(pri);
        }
    }

    /**
    检测线程组是否为当前线程组的父线程组	     */
    public final boolean parentOf(ThreadGroup g) {
        for (; g != null ; g = g.parent) {
            if (g == this) {
                return true;
            }
        }
        return false;
    }

    /**
    是否有权限取修改当前线程组
     */
    public final void checkAccess() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkAccess(this);
        }
    }

    /**
     * 返回此线程组及其子组中活动线程的估计数量。递归迭代这个线程组中的所有子组。
     */
    public int activeCount() {
        int result;
        // Snapshot sub-group data so we don't hold this lock
        // while our children are computing.
        int ngroupsSnapshot;
        ThreadGroup[] groupsSnapshot;
        synchronized (this) {
            if (destroyed) {
                return 0;
            }
            result = nthreads;
            ngroupsSnapshot = ngroups;
            if (groups != null) {
                groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
            } else {
                groupsSnapshot = null;
            }
        }
        for (int i = 0 ; i < ngroupsSnapshot ; i++) {
            result += groupsSnapshot[i].activeCount();
        }
        return result;
    }

    /**
     * 将线程组及其子线程复制到指定的数组中	     
     	     */
    public int enumerate(Thread list[]) {
        checkAccess();
        return enumerate(list, 0, true);
    }

    /**
     * 将线程组中的每个活动线程复制到指定的数组中.	     */
    public int enumerate(Thread list[], boolean recurse) {
        checkAccess();
        return enumerate(list, 0, recurse);
    }

    private int enumerate(Thread list[], int n, boolean recurse) {
        int ngroupsSnapshot = 0;
        ThreadGroup[] groupsSnapshot = null;
        synchronized (this) {
            if (destroyed) {
                return 0;
            }
            int nt = nthreads;
            if (nt > list.length - n) {
                nt = list.length - n;
            }
            for (int i = 0; i < nt; i++) {
                if (threads[i].isAlive()) {
                    list[n++] = threads[i];
                }
            }
            if (recurse) {
                ngroupsSnapshot = ngroups;
                if (groups != null) {
                    groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
                } else {
                    groupsSnapshot = null;
                }
            }
        }
        if (recurse) {
            for (int i = 0 ; i < ngroupsSnapshot ; i++) {
                n = groupsSnapshot[i].enumerate(list, n, true);
            }
        }
        return n;
    }

    /**
     * 返回这个线程组及其子组中活动组的估计数量。递归迭代这个线程组中的所有子组。
     	     */
    public int activeGroupCount() {
        int ngroupsSnapshot;
        ThreadGroup[] groupsSnapshot;
        synchronized (this) {
            if (destroyed) {
                return 0;
            }
            ngroupsSnapshot = ngroups;
            if (groups != null) {
                groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
            } else {
                groupsSnapshot = null;
            }
        }
        int n = ngroupsSnapshot;
        for (int i = 0 ; i < ngroupsSnapshot ; i++) {
            n += groupsSnapshot[i].activeGroupCount();
        }
        return n;
    }

    /**
     * 将此线程组及其子组中的每个活动子组的引用复制到指定的数组中
     *
     */
    public int enumerate(ThreadGroup list[]) {
        checkAccess();
        return enumerate(list, 0, true);
    }

    /**
     * 将此线程组中的每个活动子组的引用复制到指定的数组中.
     */
    public int enumerate(ThreadGroup list[], boolean recurse) {
        checkAccess();
        return enumerate(list, 0, recurse);
    }

    private int enumerate(ThreadGroup list[], int n, boolean recurse) {
        int ngroupsSnapshot = 0;
        ThreadGroup[] groupsSnapshot = null;
        synchronized (this) {
            if (destroyed) {
                return 0;
            }
            int ng = ngroups;
            if (ng > list.length - n) {
                ng = list.length - n;
            }
            if (ng > 0) {
                System.arraycopy(groups, 0, list, n, ng);
                n += ng;
            }
            if (recurse) {
                ngroupsSnapshot = ngroups;
                if (groups != null) {
                    groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
                } else {
                    groupsSnapshot = null;
                }
            }
        }
        if (recurse) {
            for (int i = 0 ; i < ngroupsSnapshot ; i++) {
                n = groupsSnapshot[i].enumerate(list, n, true);
            }
        }
        return n;
    }

    /**
     * 停止当前线程组中的所有线程
     */
    @Deprecated
    public final void stop() {
        if (stopOrSuspend(false))
            Thread.currentThread().stop();
    }

    /**
     * 中断线程组中的所有线程	     */
    public final void interrupt() {
        int ngroupsSnapshot;
        ThreadGroup[] groupsSnapshot;
        synchronized (this) {
            checkAccess();
            for (int i = 0 ; i < nthreads ; i++) {
                threads[i].interrupt();
            }
            ngroupsSnapshot = ngroups;
            if (groups != null) {
                groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
            } else {
                groupsSnapshot = null;
            }
        }
        for (int i = 0 ; i < ngroupsSnapshot ; i++) {
            groupsSnapshot[i].interrupt();
        }
    }

    /**
     销毁这个线程组和它的所有子组。这个线程组必须为空,表示在这个线程组中的所有线程已经停止。
     */
    public final void destroy() {
        int ngroupsSnapshot;
        ThreadGroup[] groupsSnapshot;
        synchronized (this) {
            checkAccess();
            if (destroyed || (nthreads > 0)) {
                throw new IllegalThreadStateException();
            }
            ngroupsSnapshot = ngroups;
            if (groups != null) {
                groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
            } else {
                groupsSnapshot = null;
            }
            if (parent != null) {
                destroyed = true;
                ngroups = 0;
                groups = null;
                nthreads = 0;
                threads = null;
            }
        }
        for (int i = 0 ; i < ngroupsSnapshot ; i += 1) {
            groupsSnapshot[i].destroy();
        }
        if (parent != null) {
            parent.remove(this);
        }
    }

    /**
     * 添加一个指定的线程组到当前组
    
     */
    private final void add(ThreadGroup g){
        synchronized (this) {
            if (destroyed) {
                throw new IllegalThreadStateException();  //如果已经销毁,将抛出异常信息
            }
            if (groups == null) {
                groups = new ThreadGroup[4];  //如果当前组为空
            } else if (ngroups == groups.length) {
                groups = Arrays.copyOf(groups, ngroups * 2);  //进行线程赋值
            }
            groups[ngroups] = g;

            // This is done last so it doesn't matter in case the
            // thread is killed
            ngroups++;
        }
    }

    /**
    移除当前线程组中指定的线程组
     */
    private void remove(ThreadGroup g) {
        synchronized (this) {
            if (destroyed) {
                return;
            }
            for (int i = 0 ; i < ngroups ; i++) {
                if (groups[i] == g) {
                    ngroups -= 1;
                    System.arraycopy(groups, i + 1, groups, i, ngroups - i);
                    // Zap dangling reference to the dead group so that
                    // the garbage collector will collect it.
                    groups[ngroups] = null;
                    break;
                }
            }
            if (nthreads == 0) {
                notifyAll();
            }
            if (daemon && (nthreads == 0) &&
                (nUnstartedThreads == 0) && (ngroups == 0))
            {
                destroy();
            }
        }
    }


    /**
     * 增加线程组中未启动线程的计数。未启动的线程不会被添加到线程组中,这样它们就可以被收集,如果它们从未启动,但是它们必须*计数,这样中有未启动线程的守护线程组就不会被销毁
     */
    void addUnstarted() {
        synchronized(this) {
            if (destroyed) {
                throw new IllegalThreadStateException();
            }
            nUnstartedThreads++;
        }
    }

    /**
     * 添加指定的线程到当前线程组
     */
    void add(Thread t) {
        synchronized (this) {
            if (destroyed) {
                throw new IllegalThreadStateException();
            }
            if (threads == null) {
                threads = new Thread[4];
            } else if (nthreads == threads.length) {
                threads = Arrays.copyOf(threads, nthreads * 2);
            }
            threads[nthreads] = t;

            // This is done last so it doesn't matter in case the
            // thread is killed
            nthreads++;

            // The thread is now a fully fledged member of the group, even
            // though it may, or may not, have been started yet. It will prevent
            // the group from being destroyed so the unstarted Threads count is
            // decremented.
            nUnstartedThreads--;
        }
    }

    /**
     * 通知组线程t尝试启动失败
     */
    void threadStartFailed(Thread t) {
        synchronized(this) {
            remove(t);
            nUnstartedThreads++;
        }
    }

    /**
     * 通知组线程t已经终止.
     */
    void threadTerminated(Thread t) {
        synchronized (this) {
            remove(t);

            if (nthreads == 0) {
                notifyAll();
            }
            if (daemon && (nthreads == 0) &&
                (nUnstartedThreads == 0) && (ngroups == 0))
            {
                destroy();
            }
        }
    }

    /**
     * 移除组中指定的线程t
     */
    private void remove(Thread t) {
        synchronized (this) {
            if (destroyed) {
                return;
            }
            for (int i = 0 ; i < nthreads ; i++) {
                if (threads[i] == t) {
                    System.arraycopy(threads, i + 1, threads, i, --nthreads - i);
                    // Zap dangling reference to the dead thread so that
                    // the garbage collector will collect it.
                    threads[nthreads] = null;  //设置线程为null
                    break;
                }
            }
        }
    }

    /**
     * 打印线程组的标准信息,这只能在debug模式下打印
     */
    public void list() {
        list(System.out, 0);
    }
    void list(PrintStream out, int indent) {
        int ngroupsSnapshot;
        ThreadGroup[] groupsSnapshot;
        synchronized (this) {
            for (int j = 0 ; j < indent ; j++) {
                out.print(" ");
            }
            out.println(this);
            indent += 4;
            for (int i = 0 ; i < nthreads ; i++) {
                for (int j = 0 ; j < indent ; j++) {
                    out.print(" ");
                }
                out.println(threads[i]);
            }
            ngroupsSnapshot = ngroups;
            if (groups != null) {
                groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
            } else {
                groupsSnapshot = null;
            }
        }
        for (int i = 0 ; i < ngroupsSnapshot ; i++) {
            groupsSnapshot[i].list(out, indent);
        }
    }

    /**
     *当线程组中的线程因未捕获异常而停止,且线程没有特定的异常捕获
     */
    public void uncaughtException(Thread t, Throwable e) {
        if (parent != null) {
            parent.uncaughtException(t, e);
        } else {
            Thread.UncaughtExceptionHandler ueh =
                Thread.getDefaultUncaughtExceptionHandler();
            if (ueh != null) {
                ueh.uncaughtException(t, e);
            } else if (!(e instanceof ThreadDeath)) {
                System.err.print("Exception in thread \""
                                 + t.getName() + "\" ");
                e.printStackTrace(System.err);
            }
        }
    }

     /**
     * 返回当前的线程组的String,会打印线程组的名字和最大的优先级
     */
    public String toString() {
        return getClass().getName() + "[name=" + getName() + ",maxpri=" + maxPriority + "]";
    }
}

当前类中的过时方法已经被移除,详情可以自行查看JDK 1.8 API.