gpt4 book ai didi

java - 使用时抛出 InterruptedException "Cannot find symbol"

转载 作者:太空宇宙 更新时间:2023-11-04 14:53:22 25 4
gpt4 key购买 nike

我的线程同时运行,导致它们的输出混合在一起,因此我对第一个线程进行了延迟,但我无法让它运行,因为 Java 拒绝接受 InterruptedException。以下是到目前为止我的代码:

class Evens extends Thread
{
public void run()
{
System.out.println("");
System.out.println("Even numbers between 0 and 30:");
System.out.println("");
boolean isEven;
for (int num = 0; num <=30; num++) //This for loop tests for evenness and then prints it.
{
if(num % 2 == 0)
{
isEven = true;
}
else
{
isEven = false;
}

if(isEven == true)
{
System.out.print(num + ", ");
}
else
{
}
}
}
}

class Odds extends Thread
{
public void run()
{
System.out.println("");
System.out.println("Odd numbers between 0 and 30:");
System.out.println("");
boolean isOdd;
for (int num = 0; num < 30; num++) //This for loop tests for oddness and then prints it.
{
if(num % 2 != 0)
{
isOdd = true;
}
else
{
isOdd = false;
}

if(isOdd == true)
{
System.out.print(num + ", ");
}
else
{
}
}
}
}

class Printer
{
public static void main(String args[])
{
Evens ev = new Evens();
Odds od = new Odds();
throw InterruptedException("Another string is running!");
{
ev.start();
Thread.sleep (4000);
od.start();
}
}
}

最佳答案

抛出异常时需要new关键字

throw new InterruptedException("...");

但是 sleep 会抛出自己的 InterruptedException,因此无需显式抛出异常

try {
Thread.sleep (4000);
} catch (InterruptedException e) {
...
}

阅读:Pausing Execution with Sleep

关于java - 使用时抛出 InterruptedException "Cannot find symbol",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23506028/

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