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:52:22 浏览: 46
下面是利用Runnable接口改写后的程序:
```java
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 r1 = new DelayRunnable();
DelayRunnable r2 = new DelayRunnable();
Thread thread1 = new Thread(r1);
Thread thread2 = new Thread(r2);
thread1.start();
thread2.start();
try{
Thread.sleep(1000);
} catch(InterruptedException e){
System.out.println("线程出错!");
}
}
}
```
程序会创建两个DelayRunnable对象并各自创建线程,并且每个线程都会执行10次循环,每次循环中会随机生成一个延迟时间并让线程休眠这个时间。在main函数中,程序会让主线程休眠1秒钟,以便让其他两个线程有足够的时间执行完毕。
阅读全文
相关推荐
















