gpt4 book ai didi

java - 在 Java 中创建两个线程

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:07:55 26 4
gpt4 key购买 nike

我想创建两个线程。一个线程必须打印奇数,另一个线程必须打印 1-20 之间的偶数。这是我到目前为止尝试过的代码,但没有给出预期的输出。

public class JavaApplication40 extends Thread {
@Override
public void run(){
while (true){
for (int i=0;i<=20;i++){
if(i%2!=0){
System.out.println("odd " +i);
}
}
}
}

public static void main(String[] args) {
Thread t =new JavaApplication40();

for (int x=0;x<=20;x++){
if(x%2==0){
System.out.println("even " + x);
}
}

}

}

这段代码只输出偶数。我也想要奇数。有人请告诉我如何修改上面的代码以获得预期的输出。

最佳答案

创建一个线程后,您需要调用start() 来启动它。尝试调用

t.start();

此外,您应该扩展Thread。相反,您应该实现 Runnable 并用线程包装它。此外,您无需检查值是否为奇数,或者是否确保值始终为奇数或偶数。

public class JavaApplication40 {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
public void run() {
// starting at 1 and counting by 2 is always odd
for (int i = 1; i < 10000; i += 2)
System.out.println("odd " + i);
}
});
t.start();

// starting at 0 and counting by 2 is always even
for (int x = 0; x < 10000; x+=2)
System.out.println("even " + x);
}
}

注意:使用线程的全部意义在于独立执行,线程需要时间来启动。这意味着您可以将所有偶数和所有奇数放在一起。即它打印它们的速度比线程启动的速度快。

您可能需要打印更多数字才能同时打印它们。例如10_000 而不是 20。

关于java - 在 Java 中创建两个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36668919/

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