为什么这个线程影响主线程? [英] Why is this thread affecting the main thread?
问题描述
我必须遗漏一些东西:
public class Test {
public static void main(String[] args) {
(new Thread(new Action())).run();
System.out.println("Blah");
}
}
class Action implements Runnable {
public void run() {
while (true) {
}
}
}
我创建了一个应该运行的线程一个循环。
I make a thread that is supposed to be running a loop.
在我的主线程中我打印Blah。
In my main thread I print "Blah".
然而,它永远不会被打印。为什么不?如果我做了一个单独的线程,它不应该影响我的主执行线程,对吗?
However, it is never printed. Why not? If I made a separate thread, it shouldn't affect my main execution thread, right?
这台机器有四个核心。
推荐答案
调用 start()
而不是 run()
开始一个线程。
Call start()
instead of run()
to start a thread.
简单地调用 run()
表示在同一 main中使用无限循环的方法调用
线程将阻止用 main
线程写的下一个语句。
Simply calling run()
means a method call with infinite loop in the same main
thread that will block the next statement written in main
thread.
我应该(新线程(新动作()))。start();
启动一个线程,但它仍会创建一个无限循环,新启动的线程永远不会停止。
I should be (new Thread(new Action())).start();
to start a thread but still it will create an infinite loop and the new started thread will never stop.
尝试 Thread.currentThread()。getName()
再次确认如下所示:
public void run() {
System.out.println(Thread.currentThread().getName()); // output "main"
}
线程生命周期的图形表示以及这是方法
A Pictorial Representation of Thread Life-cycle along with it's methods
这篇关于为什么这个线程影响主线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!