Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

java - Why is this thread affecting the main thread?

I must be missing something:

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.

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?

This machine has four cores.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Call start() instead of run() to start a thread.

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.

Have a look at Java Tutorial on Defining and Starting a Thread


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.

Try with Thread.currentThread().getName() to confirm it again as shown below:

public void run() {
    System.out.println(Thread.currentThread().getName()); // output "main"
}

A Pictorial Representation of Thread Life-cycle along with it's methods

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...