编写一个应用程序创建两个线程,一个线程打印输出1~1000之间所有的奇数,另外一个线程打印输出1~1000之间所有的偶数,要求两个线程随机休眠一段时间后(1秒内)继续打印输出下一个数。分别使用Runnable接口和Tread类编程实现。
时间: 2024-02-24 20:56:19 浏览: 70
使用Runnable接口实现:
```
public class PrintNumber implements Runnable {
private int start;
private int end;
private int increment;
public PrintNumber(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(Thread.currentThread().getName() + ": " + 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, 2), "Even");
Thread t2 = new Thread(new PrintNumber(2, 1000, 2), "Odd");
t1.start();
t2.start();
}
}
```
使用Thread类实现:
```
public class PrintNumber extends Thread {
private int start;
private int end;
private int increment;
public PrintNumber(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(Thread.currentThread().getName() + ": " + 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 PrintNumber("Even", 1, 1000, 2);
Thread t2 = new PrintNumber("Odd", 2, 1000, 2);
t1.start();
t2.start();
}
}
```
阅读全文