gpt4 book ai didi

java - java中的多线程示例

转载 作者:行者123 更新时间:2023-12-01 18:45:22 25 4
gpt4 key购买 nike

这是来自 tutorials point 的 java 示例程序:

// Create a new thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}

// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}

public 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(100);
}
} 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.

我无法理解为什么主线程在子线程之前执行。在程序中可以看到首先执行了new NewThread()。 NewThread 类实例化一个新线程并在新线程上调用 start() 函数,然后新线程调用 run() 函数。main 函数中的循环仅在创建新线程后才会出现。然而当程序运行时,主线程中的循环先于子线程运行。请帮我理解。

最佳答案

The loop in the main thread is run before the child thread. Please help me understand.

默认情况下,线程没有任何形式的同步,并且可以按任何顺序运行,并且执行可能会交错。您可以获取锁并使用它们来确保顺序,例如,如果主线程在启动子线程之前获取锁,则让子线程等待获取锁,并让主线程在完成其任务后释放锁.

关于java - java中的多线程示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17972373/

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