我的线程同时运行,导致它们的输出混淆,所以我在第一个线程上设置了延迟,但我无法让它运行,因为 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();
}
}
}