java创建新线程 新线程运行,Java中新创建的线程的执行顺序是什么

在Java中,创建四个线程调用同一同步方法时,线程启动的顺序由操作系统调度决定,而非Java语言规范指定。尽管预期线程会按队列顺序执行,但实际输出显示线程可能以栈的方式被处理,导致执行顺序不一致。这表明线程的并发行为受到操作系统调度的影响,不能依赖特定的执行顺序。
摘要由CSDN通过智能技术生成

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();

}

}

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?

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值