Java中编写一个应用程序创建两个线程,一个线程打印输出1~1000之间所有的奇数,另外一个线程打印输出1~1000之间所有的偶数,要求两个线程随机休眠一段时间后(1秒内)继续打印输出下一个数。分别使用Runnable接口和Tread类编程实现。
时间: 2024-02-23 22:58:53 浏览: 111
使用Runnable接口实现:
```java
public class PrintNumber implements Runnable {
private int start;
private int end;
private boolean isEven;
public PrintNumber(int start, int end, boolean isEven) {
this.start = start;
this.end = end;
this.isEven = isEven;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
if ((i % 2 == 0 && isEven) || (i % 2 == 1 && !isEven)) {
System.out.println(i);
}
try {
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new PrintNumber(1, 1000, true));
Thread t2 = new Thread(new PrintNumber(1, 1000, false));
t1.start();
t2.start();
}
}
```
使用Thread类实现:
```java
public class PrintNumber extends Thread {
private int start;
private int end;
private boolean isEven;
public PrintNumber(int start, int end, boolean isEven) {
this.start = start;
this.end = end;
this.isEven = isEven;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
if ((i % 2 == 0 && isEven) || (i % 2 == 1 && !isEven)) {
System.out.println(i);
}
try {
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
PrintNumber t1 = new PrintNumber(1, 1000, true);
PrintNumber t2 = new PrintNumber(1, 1000, false);
t1.start();
t2.start();
}
}
```
阅读全文