class DelayThread exends Thread { private static int count=0; private int no; private int delay; public DelayThread(){ count++; no=count; } public void run(){ try{ for (int i=0;i<10;i++){ delay=(int)(Math.random()*5000); sleep(delay); System.out.println(“线程”+no+“ 的延迟时间是 ”+delay); } }catch(InterruptedException e){} } } public class MyThread{ public static void main(String args[]){ DelayThread thread1=new DelayThread(); DelayThread thread2=new DelayThread(); thread1.start(); thread2.start(); try{ Thread.sleep(1000);} catch(InterruptedException e){ System.out.println(“线程出错!”); } } } 将上列程序利用Runnable接口改写,并上机检验。
时间: 2023-11-27 17:51:13 浏览: 52
常用的延时函数delay()
5星 · 资源好评率100%
下面是使用 Runnable 接口改写的程序:
```
class DelayRunnable implements Runnable {
private static int count = 0;
private int no;
private int delay;
public DelayRunnable() {
count++;
no = count;
}
public void run() {
try {
for (int i = 0; i < 10; i++) {
delay = (int) (Math.random() * 5000);
Thread.sleep(delay);
System.out.println("线程" + no + " 的延迟时间是 " + delay);
}
} catch (InterruptedException e) {
}
}
}
public class MyThread {
public static void main(String args[]) {
DelayRunnable dr1 = new DelayRunnable();
DelayRunnable dr2 = new DelayRunnable();
Thread thread1 = new Thread(dr1);
Thread thread2 = new Thread(dr2);
thread1.start();
thread2.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("线程出错!");
}
}
}
```
改写后的程序逻辑和原程序一致,只是将 DelayThread 类改为 DelayRunnable 类,并且创建线程时使用了 Runnable 接口的实现类作为参数。在主线程中也需要使用 Thread.sleep() 方法等待子线程执行完毕。
阅读全文