标签:多线程 group Thread 启动 开启 start 线程 run main
一:start()和run()的比较
代码演示
public class StartThread {
public static void main(String[] args) {
Runnable runnable = () -> {
System.out.println(Thread.currentThread().getName());
};
runnable.run();
new Thread(runnable).start();
}
}
运行结果
E:\tools\jdk1.8.0_201\bin\java.exe com.example.demo.startthread.StartThread
main
Thread-0
Process finished with exit code 0
main是 runnable.run()执行的结果,Thread-0是 new Thread(runnable).start()执行的结果。你可能会问为什么?别急,继续往下看。
二:start()方法原理解读
start()方法含义
- 启动新线程:通知JVM在有空闲的情况下就启动新线程
- 准备工作:首先它会让自己处于就绪状态,就绪状态指我已获取了除cpu以外的其他资源
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 */
}
}
}
private native void start0();
通过源码,我们可以大致的看出,start()方法在启动新线程时会首先检查线程状态(这也是为什么不能重复的执行start()方法的原因),加入线程组,最后调用start0()方法。
三: run()方法原理解读
源码
@Override
public void run() {
if (target != null) {
target.run();
}
}
可以看出这就是一个普普通通的方法,主线程main直接调用,所以打印出的线程名称是main.
我姓韩 发布了7 篇原创文章 · 获赞 6 · 访问量 142 私信 关注标签:多线程,group,Thread,启动,开启,start,线程,run,main 来源: https://blog.csdn.net/weixin_45319877/article/details/103963723
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。