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(“线程出错!”); } } } 运用Java将上列程序利用Runnable接口改写,并上机检验。
时间: 2023-11-27 20:50:55 浏览: 71
下面是使用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[]) {
Thread thread1 = new Thread(new DelayRunnable());
Thread thread2 = new Thread(new DelayRunnable());
thread1.start();
thread2.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("线程出错!");
}
}
}
```
这个程序与之前的程序功能相同,只是将DelayThread类改为了DelayRunnable类,并且使用Thread类的构造函数来创建线程。可以运行该程序进行检验。
阅读全文