gpt4 book ai didi

java - 多线程程序每次都有不同的输出

转载 作者:行者123 更新时间:2023-12-02 01:43:20 25 4
gpt4 key购买 nike

当我尝试多次执行以下多线程代码时,输​​出与前一个不同。这是因为 JVM 行为还是其他原因。请帮我一个。

program:


package example.thread.com;

class MyThread1 implements Runnable {
Thread t;

MyThread1(String s) {
t = new Thread(this, s);
t.start();
}

public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread Name :"
+ Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (Exception e) {
}
}
}
}


public class RunnableThread1 {
public static void main(String args[]) {
System.out.println("Thread Name :" + Thread.currentThread().getName());
MyThread1 m1 = new MyThread1("My Thread 1");
MyThread1 m2 = new MyThread1("My Thread 2");
}
}

输出:如果我第一次运行

Thread Name :main
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 2

输出:如果我第二次运行

Thread Name :main
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 2

输出:如果我第三次运行

Thread Name :main
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 1

像这样请推荐......

最佳答案

这正是示例的要点。它表明线程是随心所欲地调度的,并且不能保证输出按顺序发生。

在其他编程语言和系统中,期望损坏的输出并非没有道理,例如:

Thread Name :main
Thread Name :My Thread 1
Thread NThread Name :My Thread 2ame :My Thread 2
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Name :My Thread 1
ThreaThread Name :My d Name :My ThrThread 2ead 1
Thread Name :My Thread 2
Thread Name :My Thread 1

关于java - 多线程程序每次都有不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57476412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com