java Thread 如何定时执行
时间: 2023-08-22 21:08:24 浏览: 54
Java中,有多种方式可以实现线程的定时执行:
1. 使用Thread.sleep()方法进行休眠,让线程在指定时间后再次执行。这种方式比较简单,但是容易受到其他线程的影响,时间不太准确。
2. 使用Timer类,通过它可以在指定时间间隔内执行任务。Timer类可以实现定时、延时等功能,但是不能确保任务的执行时间。
3. 使用ScheduledExecutorService类,它是Executor框架的一个扩展,可以用来处理延时任务和定期任务。这种方式可以确保任务的执行时间,而且具有更好的灵活性和可控性。
下面是使用ScheduledExecutorService类实现线程的定时执行的示例代码:
```java
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class MyThread implements Runnable {
@Override
public void run() {
System.out.println("执行定时任务");
}
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(new MyThread(), 0, 5, TimeUnit.SECONDS); //每5秒执行一次任务
}
}
```
在上面的示例中,我们创建了一个ScheduledExecutorService对象,并通过scheduleAtFixedRate()方法指定了任务的执行时间间隔为5秒。程序会在启动后立即执行一次任务,然后每隔5秒再次执行任务。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)