java - 在线程内使用 System.exit() 后显示主线程的输出

标签 java multithreading

我正在学习 Java 中的线程。我刚刚创建了一个新线程,那里很好,我希望程序在完成某些操作时关闭,但是当我在线程内调用 System.exit(0); 时,程序不会关闭!

代码:

public class Humaida
{
    public Thread thread;
    public Humaida()
    {
        thread = new Thread(() ->              //i guess it using lambda expression,i just copied it
        {
            try
            {
                System.out.println("inside thread");
                System.exit(0);            // i think this line have to close\terminate JVM or the whole program
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        });
        thread.start();                           //IMO this should be last line to execute

        System.out.println("after thread.start"); //shouldn't be run cause System.exit(0); reached

        printIt("after reading thread");          // i used my method just to ensure that program running
    }

    public static void main(String[] args)
    {
        new Humaida();
    }

    public void printIt(String text)
    {
        System.out.println(text);
    }
}

我得到一些奇怪的输出,例如

1st run:
after thread.start
inside thread
Press any key to continue . . .

 2nd run:
after thread.start
after reading thread
inside thread
Press any key to continue . . .

3rd run:
after thread.start
inside thread
after reading thread
Press any key to continue . . .

让我们忘记相同代码的不同输出,这是另一个问题。

我搜索了一些解决方案,我尝试了 System.exit(-1);thread.kill() 但它也不起作用。

这里发生了什么?

System.exit(0); 是否只是终止该线程,而不是主线程?

最佳答案

线程的目的是并行地做事情。您看到的是竞争条件。

当您执行thread.start();时,它将开始运行线程中的代码而且立即继续使用System.out。 println("thread.start 之后"); 语句。这就是为什么您可能会看到两者。

如果你想等到线程完成,你可以这样做:

    thread.start();                           
    try {
      System.out.println("Main thread waiting for new thread to finish");
      thread.join();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

在这种情况下,您将看到整个虚拟机在线程完成之前退出。

关于java - 在线程内使用 System.exit() 后显示主线程的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52897390/

相关文章:

java - 动态加载模板文件到 Rythm? (无需目录设置)

java - 如何从 Guice 中按类获取对象列表?

ios - 多线程违规留给我们的只是荣誉(失败)

c# 线程和等待表单

Java线程运行顺序

java - 类图中的public、protection、private的作用是什么?有什么例子吗?

java - 从 Jar 文件中使用 Thymeleaf 模板

java - Joptionpane弹出窗口

JAVA线程池复用线程

c++ - 这种无锁设计线程安全吗?