JAVA启动两个线程,每个线程均输出线程名和系统当前日期时间各5次,名为“Fast Thread”的线程每隔1秒钟输出,名为“Slow Thread”的线程每隔3秒钟输出
时间: 2024-05-08 22:21:12 浏览: 77
可以使用Thread类和Runnable接口来创建两个线程,然后在每个线程的run方法中使用while循环和Thread.sleep方法来实现定时输出。
以下是示例代码:
```
public class Main {
public static void main(String[] args) {
Thread fastThread = new Thread(new FastThread());
Thread slowThread = new Thread(new SlowThread());
fastThread.start();
slowThread.start();
}
}
class FastThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Fast Thread: " + new Date());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class SlowThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Slow Thread: " + new Date());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
输出示例:
```
Fast Thread: Mon Oct 11 14:39:21 CST 2021
Slow Thread: Mon Oct 11 14:39:21 CST 2021
Fast Thread: Mon Oct 11 14:39:22 CST 2021
Fast Thread: Mon Oct 11 14:39:23 CST 2021
Slow Thread: Mon Oct 11 14:39:24 CST 2021
Fast Thread: Mon Oct 11 14:39:24 CST 2021
Fast Thread: Mon Oct 11 14:39:25 CST 2021
Slow Thread: Mon Oct 11 14:39:27 CST 2021
Fast Thread: Mon Oct 11 14:39:26 CST 2021
Slow Thread: Mon Oct 11 14:39:30 CST 2021
Fast Thread: Mon Oct 11 14:39:27 CST 2021
Fast Thread: Mon Oct 11 14:39:28 CST 2021
Slow Thread: Mon Oct 11 14:39:33 CST 2021
Fast Thread: Mon Oct 11 14:39:29 CST 2021
Slow Thread: Mon Oct 11 14:39:36 CST 2021
Fast Thread: Mon Oct 11 14:39:30 CST 2021
Slow Thread: Mon Oct 11 14:39:39 CST 2021
Fast Thread: Mon Oct 11 14:39:31 CST 2021
Slow Thread: Mon Oct 11 14:39:42 CST 2021
```
阅读全文