1. 编写在构造方法中产生一个1-5之间的随机数的继承Thread类的线程类DelayPrintThread,使得线程体每休眠此随机数时间就打印输出线程号和休眠时间;另外编写应用DelayPrintThread类的Java应用程序TwoThread.java,在main()方法中创建两个线程,并应用sleep()控制主应用程序延迟一段时间。
时间: 2023-06-27 07:07:49 浏览: 160
DelayPrintThread类的代码如下:
```java
import java.util.Random;
public class DelayPrintThread extends Thread {
private int threadNum;
private Random random;
public DelayPrintThread(int threadNum) {
this.threadNum = threadNum;
this.random = new Random();
}
@Override
public void run() {
try {
int sleepTime = random.nextInt(5) + 1;
Thread.sleep(sleepTime * 1000);
System.out.println("Thread " + threadNum + " sleeps for " + sleepTime + " seconds.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
TwoThread.java应用程序的代码如下:
```java
public class TwoThread {
public static void main(String[] args) {
DelayPrintThread thread1 = new DelayPrintThread(1);
DelayPrintThread thread2 = new DelayPrintThread(2);
thread1.start();
thread2.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
在这个应用程序中,我们创建了两个DelayPrintThread线程,并且启动它们。在主程序中,我们使用Thread.sleep()方法来控制主线程延迟10秒钟,以便我们能够看到两个线程的输出结果。
阅读全文