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(“线程出错!”); } } }创建简单的程序,创建三个线程,每个线程应当显示它从开始到目前为止累计运行时间(可以考虑使用Date类或Calendar类)。
时间: 2023-11-27 10:52:52 浏览: 28
以下是代码实现:
```
import java.util.Calendar;
class RunningTimeThread extends Thread {
private static int count = 0;
private int no;
private Calendar startTime;
public RunningTimeThread() {
count++;
no = count;
startTime = Calendar.getInstance();
}
public void run() {
try {
for (int i = 0; i < 10; i++) {
Thread.sleep((int)(Math.random()*5000));
Calendar now = Calendar.getInstance();
long diff = now.getTimeInMillis() - startTime.getTimeInMillis();
System.out.println("线程" + no + "的运行时间是 " + diff + "毫秒");
}
} catch(InterruptedException e) {}
}
}
public class MyThread {
public static void main(String args[]) {
RunningTimeThread thread1 = new RunningTimeThread();
RunningTimeThread thread2 = new RunningTimeThread();
RunningTimeThread thread3 = new RunningTimeThread();
thread1.start();
thread2.start();
thread3.start();
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println("线程出错!");
}
}
}
```
程序中创建了一个 `RunningTimeThread` 类,该类继承自 `Thread`。在 `RunningTimeThread` 类中使用 `Calendar` 类记录线程的开始时间,并在 `run` 方法中计算线程的运行时间。在主线程中创建三个 `RunningTimeThread` 线程,并启动它们。最后主线程等待1秒后结束。