gpt4 book ai didi

java - java中如何同时运行两个线程

转载 作者:搜寻专家 更新时间:2023-10-31 08:25:37 26 4
gpt4 key购买 nike

我是 java 的新手,我正在尝试了解线程。

我期待备用hello this is thread onehello this is thread 2 的输出。但我得到的输出如下:

hello this is thread one
hello this is thread one
hello this is thread one
hello this is thread one
hello this is thread one
hello this is thread two
hello this is thread two
hello this is thread two
hello this is thread two
hello this is thread two

下面是我的代码。谁能帮我弄清楚为什么我得到的输出与预期相反。我可以做什么来并行运行这两个线程。

public class ThreadDemo {
public static void main(String args[]) {

// This is the first block of code
Thread thread = new Thread() {
public void run() {
for (int i = 0; i < 10; i += 2) {
System.out.println("hello this is thread one");
}
}
};

// This is the second block of code
Thread threadTwo = new Thread() {
public void run() {
for (int i = 0; i < 10; i += 2) {
System.out.println("hello this is thread two");
}
}
};

// These two statements are in the main method and begin the two
// threads.
// This is the third block of code
thread.start();

// This is the fourth block of code
threadTwo.start();
}
}

最佳答案

仅仅因为线程可能交错并不意味着它们将会。您的线程运行得太快了。尝试添加 Thread.sleep() 让它们运行更长时间。

关于java - java中如何同时运行两个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34434543/

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