用java编写创建三个线程,每个线程应当显示它从开始到目前为止累计运行时间(可以考虑使用Date类或Calendar类)
时间: 2023-11-27 09:50:02 浏览: 82
可以使用Java中的Thread类来创建线程,使用System.currentTimeMillis()方法获取当前时间戳,然后进行时间的计算。以下是示例代码:
```java
import java.util.Calendar;
import java.util.Date;
public class ThreadDemo {
public static void main(String[] args) {
Thread t1 = new Thread(new MyThread("Thread 1"));
Thread t2 = new Thread(new MyThread("Thread 2"));
Thread t3 = new Thread(new MyThread("Thread 3"));
t1.start();
t2.start();
t3.start();
}
}
class MyThread implements Runnable {
private String name;
private long startTime;
public MyThread(String name) {
this.name = name;
this.startTime = System.currentTimeMillis();
}
@Override
public void run() {
while (true) {
long currentTime = System.currentTimeMillis();
long timeDiff = currentTime - startTime;
Date date = new Date(timeDiff);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
System.out.println(name + " has been running for " + hour + " hour(s), " + minute + " minute(s), " + second + " second(s).");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
上述代码中,我们创建了一个MyThread类实现了Runnable接口,在run()方法中不断计算线程运行时间,并打印出来。在ThreadDemo类中,我们创建了三个线程,分别启动它们。运行程序后,我们可以看到每个线程不断打印出它们的运行时间。
阅读全文