Java多线程-03之-Thread中start()和run()的区别

start()和run()方法的区别

start(): 它的作用是启动一个新线程,新线程会执行相应的run()方法。start()不能被重复调用。

run(): run()就和普通的成员方法一样,可以被重复调用。单独调用run()的话,会在当前线程中执行run(),而并不会启动新线程!

下面以代码来进行说明。

1
2
3
4
5
6
class MyThread extends Thread{  
public void run(){
...
}
};
MyThread mythread = new MyThread();

mythread.start()会启动一个新线程,并在新线程中运行run()方法。
而mythread.run()则会直接在当前线程中运行run()方法,并不会启动一个新线程来运行run()。

start()和run()方法示例

下面,通过一个简单示例演示它们之间的区别。源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class TestThread extends Thread {
public TestThread(String name) {
super(name);
}

@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is running");
}
};

public class ThreadMethodDemo {
public static void main(String[] args) {
Thread mythread = new TestThread("testThread");

System.out.println(Thread.currentThread().getName() + " call testThread.run()");
mythread.run();

System.out.println(Thread.currentThread().getName() + " call testThread.start()");
mythread.start();
}
}

运行结果:

1
2
3
4
main call testThread.run()
main is running
main call testThread.start()
testThread is running

结果说明:
1) Thread.currentThread().getName()是用于获取“当前线程”的名字。当前线程是指正在cpu中调度执行的线程。
2) testThread.run()是在“主线程main”中调用的,该run()方法直接运行在“主线程main”上。
3) testThread.start()会启动“线程testThread”,“线程testThread”启动之后,会调用run()方法;此时的run()方法是运行在“线程testThread”上。

start()和run()源码说明(基于JDK1.8.0_171)

  • 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
24
25
26
27
28
public synchronized void start() {
/**
* 如果线程不是"新建状态",则抛出异常
* 状态值0 对应"新建"
*/
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) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}

说明:

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()方法,并不会新建一个线程。

本文标题:Java多线程-03之-Thread中start()和run()的区别

文章作者:王洪博

发布时间:2018年05月29日 - 23:05

最后更新:2019年09月12日 - 10:09

原始链接:http://whb1990.github.io/posts/22f6e11d.html

▄︻┻═┳一如果你喜欢这篇文章,请点击下方"打赏"按钮请我喝杯 ☕
0%