java 编写一个应用程序创建两个线程,一个线程打印输出1~1000之间所有的奇数,另外一个线程打印输出1~1000之间所有的偶数,要求两个线程随机休眠一段时间后(1秒内)继续打印输出下一个数。分别使用Runnable接口和Tread类编程实现。
时间: 2024-02-23 20:58:23 浏览: 92
Java实现多线程轮流打印1-100的数字操作
使用Runnable接口实现:
```java
public class PrintOddEven implements Runnable {
private int start;
private int end;
private boolean isOdd;
public PrintOddEven(int start, int end, boolean isOdd) {
this.start = start;
this.end = end;
this.isOdd = isOdd;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
if (isOdd && i % 2 != 0) {
System.out.println(Thread.currentThread().getName() + " : " + i);
} else if (!isOdd && i % 2 == 0) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
try {
Thread.sleep((long)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
PrintOddEven odd = new PrintOddEven(1, 1000, true);
PrintOddEven even = new PrintOddEven(1, 1000, false);
Thread oddThread = new Thread(odd, "Odd");
Thread evenThread = new Thread(even, "Even");
oddThread.start();
evenThread.start();
}
}
```
使用Thread类实现:
```java
public class PrintOddEven extends Thread {
private int start;
private int end;
private boolean isOdd;
public PrintOddEven(int start, int end, boolean isOdd) {
this.start = start;
this.end = end;
this.isOdd = isOdd;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
if (isOdd && i % 2 != 0) {
System.out.println(Thread.currentThread().getName() + " : " + i);
} else if (!isOdd && i % 2 == 0) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
try {
Thread.sleep((long)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
PrintOddEven odd = new PrintOddEven(1, 1000, true);
PrintOddEven even = new PrintOddEven(1, 1000, false);
odd.start();
even.start();
}
}
```
注意,两种实现方式的核心代码是相同的。
阅读全文