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(Stringargs[]){ 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 11:50:46 浏览: 30
以下是利用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 runnable1 = new DelayRunnable();
DelayRunnable runnable2 = new DelayRunnable();
Thread thread1 = new Thread(runnable1);
Thread thread2 = new Thread(runnable2);
thread1.start();
thread2.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("线程出错!");
}
}
}
```
通过将DelayThread类改写为DelayRunnable实现了Runnable接口,然后在MyThread类中创建两个DelayRunnable对象,分别将它们作为Thread的构造函数参数来创建线程对象,并调用start()方法启动线程。最后通过Thread.sleep()方法使主线程睡眠1秒钟。