JAVA启动两个线程,每个线程均输出线程名和系统当前日期时间各5次,名为“Fast Thread”的线程每隔1秒钟输出,名为“Slow Thread”的线程每隔3秒钟输出
时间: 2024-05-01 17:23:57 浏览: 20
下面是一个示例代码实现:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
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() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (int i = 0; i < 5; i++) {
System.out.println("Fast Thread: " + sdf.format(new Date()));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class SlowThread implements Runnable {
@Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (int i = 0; i < 5; i++) {
System.out.println("Slow Thread: " + sdf.format(new Date()));
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
输出结果如下:
```
Fast Thread: 2021-10-08 18:06:19
Slow Thread: 2021-10-08 18:06:19
Fast Thread: 2021-10-08 18:06:20
Fast Thread: 2021-10-08 18:06:21
Slow Thread: 2021-10-08 18:06:22
Fast Thread: 2021-10-08 18:06:22
Fast Thread: 2021-10-08 18:06:23
Slow Thread: 2021-10-08 18:06:25
Fast Thread: 2021-10-08 18:06:24
Slow Thread: 2021-10-08 18:06:28
Fast Thread: 2021-10-08 18:06:25
Slow Thread: 2021-10-08 18:06:31
Fast Thread: 2021-10-08 18:06:26
Slow Thread: 2021-10-08 18:06:34
Fast Thread: 2021-10-08 18:06:27
Slow Thread: 2021-10-08 18:06:37
```