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 21:51:05 浏览: 28
以下是使用 Runnable 接口改写的代码:
```
class DelayThread implements Runnable {
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);
Thread.sleep(delay);
System.out.println("线程" + no + " 的延迟时间是 " + delay);
}
} catch (InterruptedException e) {}
}
}
public class MyThread {
public static void main(String args[]) {
DelayThread delayThread1 = new DelayThread();
DelayThread delayThread2 = new DelayThread();
Thread thread1 = new Thread(delayThread1);
Thread thread2 = new Thread(delayThread2);
thread1.start();
thread2.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("线程出错!");
}
}
}
```
在这个改写后的代码中,DelayThread 类现在实现了 Runnable 接口,run() 方法也被重写了。在 main() 方法中,我们创建了两个 DelayThread 的实例,并将它们传递给了两个 Thread 实例,然后启动这两个线程。
请注意,我们必须显式地调用 Thread.sleep() 方法,而不是使用 sleep() 静态方法。这是因为我们没有继承 Thread 类,所以没有办法直接访问 sleep() 静态方法。