用Thread类实现线程创建启动之后创建3个线程每一个休眠(0~6)秒后结束,休眠可用Thread.sleep.(long.milllis)函数
时间: 2024-09-19 20:17:35 浏览: 36
JVM线程状态和Thread.sleep的实现原理探究.pdf
当使用Java的`Thread`类创建线程时,可以按照以下步骤实现这个需求:
首先,需要创建一个实现了`Runnable`接口的类,用于封装线程的任务逻辑,这里我们将其命名为`TaskRunner`:
```java
public class TaskRunner implements Runnable {
private int sleepTime;
public TaskRunner(int sleepTime) {
this.sleepTime = sleepTime;
}
@Override
public void run() {
try {
System.out.println("Thread starting with " + sleepTime + " seconds to sleep.");
Thread.sleep(sleepTime * 1000); // 将秒转换为毫秒
System.out.println("Thread finished sleeping.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
接着,在主程序中创建三个这样的线程,并设置它们各自的休眠时间:
```java
public class Main {
public static void main(String[] args) {
Thread thread1 = new Thread(new TaskRunner(0));
Thread thread2 = new Thread(new TaskRunner(3));
Thread thread3 = new Thread(new TaskRunner(6));
// 启动线程
thread1.start();
thread2.start();
thread3.start();
// 等待所有线程执行完毕
try {
thread1.join();
thread2.join();
thread3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All threads have completed.");
}
}
```
在这个例子中,每个线程会打印开始睡觉的消息,然后休眠指定的时间,最后打印完成消息。注意,`join()`方法用于让主线程等待其他线程执行完。
阅读全文