Java多线程-启动线程
# Java多线程02-启动线程
java启动线程有两个方法:
- start()
- run()
public class StartAndRunMethod {
public static void main(String[] args) {
Runnable runnable = () -> {
System.out.println(Thread.currentThread().getName());
};
runnable.run();
new Thread(runnable).start();
}
}
# start()方法原理
start
方法就是去启动新线程,执行流程如下:
- 检查线程状态,只有NEW状态下的线程才能继续,否则会抛出IllegalThreadStateException异常。
- 加入到线程组。
- 调用start0()方法启动线程。
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 then
it will be passed up the call stack */
}
}
}
# run()方法原理
@Override
public void run() {
if (target != null) {
target.run();
}
}
run()方法会根据传入的对象执行不同结果
# 小结
start()才是真正启动一个线程,而如果直接调用run(),那么run只是一个普通的方法而已,和线程的生命周期没有任何关系。
上次更新: 2024/06/29, 15:13:44