java线程执行顺序

标签 java multithreading

public class SousThread implements Runnable {
    private int i;

    public SousThread() {
        this.i = 0;
    }

    @Override
    public void run() {
        while(true) {
            System.out.println("I'm sousthread " + i++);
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class TestThread implements Runnable {

    @Override
    public void run() {
        System.out.println("I'm thread");
        SousThread st = new SousThread();
        Thread td = new Thread(st);
        td.start();
        System.out.println("thread finished");
    }

    public static void main(String[] args) {
        TestThread tt = new TestThread();
        Thread td = new Thread(tt);
        td.start();
        System.out.println("main finished");
    }
}

我正在尝试在线程 TestThread 中创建线程 SousThreadSousThread 是无限的。

令我惊讶的是,我得到了以下结果:

I'm thread
main finished
thread finished
I'm sousthread 0
I'm sousthread 1
I'm sousthread 2
I'm sousthread 3
I'm sousthread 4
I'm sousthread 5
...
...

这是否意味着方法main已完成而线程尚未完成?这可能吗?这安全吗?如果没有,更好的方法是什么?

更新

因为这样的代码在 C++ 中不起作用。所以我只想知道代码在 Java 中是否可以正常运行,没有任何问题或风险。

最佳答案

这是well documented完全正常:

When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:

  • The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
  • All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.

在您的情况下,虽然主线程已终止(通过 main() 返回隐式终止),但其他线程仍然处于 Activity 状态。除非您在某处调用 System.exit() 或将其他线程设置为守护线程,否则 JVM 将继续运行,直到所有线程都加入。

如果您希望所有线程在主线程存在之前终止,则需要 Thread.join()他们。请注意Runtime.exit()非常严厉地终止线程。线程是 not interrupted nor are their finalizers called ,所以这确实不安全。

关于java线程执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43009656/

相关文章:

java - JHipster UserService - 变量可能尚未初始化

java - MongoDB聚合条件转换为JAVA驱动程序

java - 为什么在多线程工作时调试不能正常工作

c# - 执行异步 RIA 服务调用时回调在哪个线程上执行?

java - 谷歌应用程序引擎-Java : HTML Error 403: Configuration Solution Thread

java - 如何重新启动 AsyncTask 或避免 RUNNING

java - 使用 Castor 解码时出现 NoClassDefFoundError

c++ - 如何通过 QtConcurrent 调用带参数的函数

c - 生产者消费者问题

c++ - 线程安全 : Multiple threads reading from a single const source