Java中新创建的线程的执行顺序是什么 [英] What is the order of execution of newly created threads in java

查看:203
本文介绍了Java中新创建的线程的执行顺序是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Test {
    boolean isFirstThread = true;

    private synchronized void printer(int threadNo) {
        if(isFirstThread) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        isFirstThread = false;
        System.out.println(threadNo);
   }

   public void starter() {
        new Thread(){
            @Override()
            public void run() {
                printer(0);
            }
        }.start();

        new Thread(){
            @Override()
            public void run() {
                printer(1);
            }
        }.start();

        new Thread(){
            @Override()
            public void run() {
                printer(2);
            }
        }.start();

        new Thread(){
            @Override()
            public void run() {
                printer(3);
            }
        }.start();
    }
}

在上面的代码中,当我从main调用启动器时.我创建了四个新线程来调用同步函数.我知道无法预测线程的执行顺序.除非它们全部等待一段时间,否则第一个线程可以完成并从同步块中退出.在这种情况下,我希望所有线程都保留在队列中,所以我希望答案为
0
1
2
3
但是始终如一(我运行程序超过20次)我得到的输出是
0
3
2
1
这意味着线程被保存在堆栈中而不是队列中.为什么会这样呢?谷歌结果中的每个答案都说这是一个队列,但我将其作为堆栈.我想知道将线程保持在堆栈中的原因(这很直观),而不是队列?

In the above code, when i call starter from main. I have created four new Threads to call a synchronized function. I know the order of execution of the threads can't be predicted. Unless they all wait for some time, so that first thread can finish and come out of the synchronized block. In which case I expect all threads to be held in a queue so i expected the answer as
0
1
2
3
But consistently(I ran the program more than 20 times) I was getting the output as
0
3
2
1
Which means that the threads are being held in a stack instead of a queue. Why is it so? Every answer in the google result says it is a queue but I am getting it as a stack. I would like to know the reason behind for holding the threads in stack(which is counter intuitive) instead of queue?

推荐答案

线程启动的顺序取决于操作系统,Java语言规范中未指定.您在主线程中调用start,但是当新线程被分配并开始处理时,其Runnable或run方法将留给操作系统的调度程序来决定.

The order in which threads start is up to the OS, it is not specified in the Java Language Spec. You call start in the main thread, but when the new thread gets allocated and when it begins processing its Runnable or run method is left to the OS' scheduler to decide.

请注意不要依赖于线程启动的顺序.

Be careful not to rely on the order in which threads happen to start.

这篇关于Java中新创建的线程的执行顺序是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆