创建简单程序,创建三个线性程,每一个线程应当显示它从开始到目前为止累积运行时间(可以考虑使用Date类或Calendar类)程序文件保存为EX9_3)
时间: 2023-11-27 17:52:59 浏览: 75
以下是一个使用Date类的Java程序,创建三个线程并显示它们的累积运行时间:
```java
import java.util.Date;
public class EX9_3 {
public static void main(String[] args) {
Thread t1 = new Thread(new Timer("Thread 1"));
Thread t2 = new Thread(new Timer("Thread 2"));
Thread t3 = new Thread(new Timer("Thread 3"));
t1.start();
t2.start();
t3.start();
}
static class Timer implements Runnable {
private String name;
private Date startTime;
public Timer(String name) {
this.name = name;
this.startTime = new Date();
}
@Override
public void run() {
long totalTime = 0;
while (true) {
Date currentTime = new Date();
long elapsedTime = currentTime.getTime() - startTime.getTime();
totalTime += elapsedTime;
System.out.println(name + " has been running for " + totalTime + " milliseconds.");
startTime = currentTime;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
```
该程序创建了三个线程,并在每个线程的run方法中使用Date类计算累积运行时间。每个线程会每秒钟输出一次它的累积运行时间。
阅读全文