编写一个应用程序创建两个线路,一个线程打印输出1~1000之间所有的奇数,另外一个线程打印输出1~1000之间所有的偶数,要求两个线程随机休眠一段时间后(1秒内)继续打印输出下一个数。分别用Runnable接口和Tread类编程实验。
时间: 2024-02-23 14:58:54 浏览: 66
使用Runnable接口:
```java
public class NumberPrinter implements Runnable {
private int start;
private int end;
private int increment;
public NumberPrinter(int start, int end, int increment) {
this.start = start;
this.end = end;
this.increment = increment;
}
@Override
public void run() {
for (int i = start; i <= end; i += increment) {
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 oddThread = new Thread(new NumberPrinter(1, 1000, 2));
Thread evenThread = new Thread(new NumberPrinter(2, 1000, 2));
oddThread.start();
evenThread.start();
}
}
```
使用Thread类:
```java
public class NumberPrinter extends Thread {
private int start;
private int end;
private int increment;
public NumberPrinter(String name, int start, int end, int increment) {
super(name);
this.start = start;
this.end = end;
this.increment = increment;
}
@Override
public void run() {
for (int i = start; i <= end; i += increment) {
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 oddThread = new NumberPrinter("OddThread", 1, 1000, 2);
Thread evenThread = new NumberPrinter("EvenThread", 2, 1000, 2);
oddThread.start();
evenThread.start();
}
}
```
阅读全文