Thread中start()和run()的区别

start() 和 run()的区别示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 最常见的两种方法启动新的线程
public static void startThread() {
// 1) 覆盖 run 方法
new Thread() {
@Override
public void run() {
// 耗时操作
}
}.start();
// 2) 传入 Runnable 对象
new Thread(new Runnable() {
public void run() {
// 耗时操作
}
}).start();
}

start() 和 run()相关源码

Thread.java中start()方法的源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public synchronized void start() {
// 如果线程不是"就绪状态",则抛出异常!
if (threadStatus != 0)
throw new IllegalThreadStateException();
// 将线程添加到ThreadGroup中
group.add(this);
boolean started = false;
try {
// 通过start0()启动线程
start0();
// 设置started标记
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
}
}
}

说明:start()实际上是通过本地方法start0()启动线程的。而start0()会新运行一个线程,新线程会调用run()方法。

1
private native void start0();

Thread.java中run()的代码如下:

1
2
3
4
5
public void run() {
if (target != null) {
target.run();
}
}

说明:target是一个Runnable对象。run()就是直接调用Thread线程的Runnable成员的run()方法,并不会新建一个线程。

参考:

https://github.com/xcc3641/hexo_blog/blob/master/source/_posts/Review-Java-Thread-1.md

http://www.jianshu.com/p/81a56497e073

热评文章