java编写三个线程分别显示各自的运行时间,第一个线程每隔1秒钟运行一次,第二个线程每隔5秒钟运行一次,第三个线程每隔10秒钟运行一次
时间: 2023-12-29 13:17:42 浏览: 201
三线程分别显示各自时间
好的,以下是Java代码实现:
```java
public class TimeThread implements Runnable {
private String threadName;
private int interval;
public TimeThread(String name, int interval) {
this.threadName = name;
this.interval = interval;
}
@Override
public void run() {
System.out.println(threadName + " is running...");
int count = 0;
while(true) {
try {
Thread.sleep(interval * 1000);
count += interval;
System.out.println(threadName + " has been running for " + count + " seconds.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
然后在主函数中创建三个线程并启动:
```java
public static void main(String[] args) {
Thread t1 = new Thread(new TimeThread("Thread-1", 1));
Thread t2 = new Thread(new TimeThread("Thread-2", 5));
Thread t3 = new Thread(new TimeThread("Thread-3", 10));
t1.start();
t2.start();
t3.start();
}
```
这样就可以实现三个线程分别显示各自的运行时间,第一个线程每隔1秒钟运行一次,第二个线程每隔5秒钟运行一次,第三个线程每隔10秒钟运行一次了。
阅读全文