Java两种创建线程方式原理解析

首先,想这样一个问题:在Java中创建并执行线程任务的方式有哪几种?

  回忆下,你应该很快就能想起来我们在Java中创建线程的方式有两种:

  • 继承Thread类并重写run()方法,要执行的任务写在run()方法中,然后new 出该类的对象,并调用其start()方法。
  • 实现Runnable接口,并重写其run()方法,要执行的任务写在run()方法中,然后将实例化的Runnable对象以参数的形式传给Thread对象,然后调用Thread.start()方法。

  下面就是两种创建并启动线程的两种写法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class Main {
public static void main(String[] args){
new SubThread().start();
new Thread(new ImplRunnable()).start();
}
/**
* 实现Runnable接口
*/
private static class ImplRunnable implements Runnable{
@Override
public void run() {
System.out.println("implements Runnable ");
}
}
/**
* 继承Thread类
*/
public static class SubThread extends Thread {
@Override
public void run() {
super.run();
System.out.println("class extends Thread");
}
}
}

原理

 在知道两种创建线程的方法后,那么就要想想,为什么这两种方式都是可以创建线程呢?

首先,看图说话,先看下Thread启动的序列图

sequency_thread

  • 在主线程中通过调用子线程的start()方法启动子线程;
  • Java虚拟机会调用子线程的run()方法,在子线程的run()方法中判断Runnable对象不为空时,调用Runnable的run()方法。

整体的流程很简单,下面我们通过源码来看具体的实现。

我们知道启动线程是调用了Thread.start()方法,那么我们就从start()方法开始,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* 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()
*/
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(); //native 方法,真正start线程实现
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 */
}
}
}

start()方法体中的内容,我们不需要关心,主要看方法的说明,里面有提到JVM会调用Thread的run()方法。那么我们接着看run()方法的内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 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)
*/
@Override
public void run() {
if (target != null) {
target.run();
}
}

重点还是看方法的说明:

  • 如果在Thread构造方法中传入了Runnable对象,那么会调用Runnable的run()方法;
  • 如果是继承Thread类,那么子类应该重写run()方法。

我们可以从Thread(Runnable target)构造方法入手,看下target对象是怎么初始化的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
public Thread(Runnable target) {
init(null, target, "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);
}
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; // 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();
}

总结

  在了解两种创建并启动线程的两种方式后,可以去看看Thread的类,类说明里面有提到:

1
2
3
4
* There are two ways to create a new thread of execution. One is to
* declare a class to be a subclass of <code>Thread</code>. This
* subclass should override the <code>run</code> method of class
* <code>Thread</code>.

其实,在继承Thread后也可以完全不用重写run()方法,照样可以执行线程的内容。只不过是要修改过下子类的构造方法,比如把开头的例子改成这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Main {
public static void main(String[] args){
new SubThread(new ImplRunnable()).start();
new Thread(new ImplRunnable()).start();
}
/**
* 实现Runnable接口
*/
private static class ImplRunnable implements Runnable{
@Override
public void run() {
System.out.println("implements Runnable ");
}
}
/**
* 继承Thread类
*/
public static class SubThread extends Thread {
public SubThread(Runnable runnable){
super(runnable);
}
}
}

为什么这样也可以,相信看完这篇文件你肯定能明白的。至于这样方式是否优雅,反正我是不太喜欢的,只是动点逆向思维,just for fun…