gpt4 book ai didi

java - 了解Java中多线程的概念

转载 作者:行者123 更新时间:2023-11-30 05:59:31 25 4
gpt4 key购买 nike

最近我完成了一个简单的线程程序,这给我带来了一些相关概念的问题......我的示例程序代码如下所示:

class NewThread implements Runnable {
Thread t;
NewThread() {
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
public void run() {
try {
for (int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for (int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

现在这个程序给我的输出如下:

Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

所以,这对我来说非常清楚。但是,一旦我将对象创建代码(调用 NewThread 类构造函数)替换为如下所示:

NewThread nt = new NewThread(); // create a new thread

输出变得有点不同,如下所示:

Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Child Thread: 3
Main Thread: 4
Child Thread: 2
Child Thread: 1
Main Thread: 3
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
有时,这两种情况都会给我相同的输出。因此,我在这两种情况下都没有得到确切的变化。

我想知道输出的变化是在这里吗?

提前致谢...

最佳答案

改变的输出是由于操作系统进程调度和 JVM 线程调度的性质造成的。即使您取出第二个线程,也不能保证您的线程会在 500 毫秒后准确唤醒。

关于java - 了解Java中多线程的概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3051284/

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