Java延時(shí)執(zhí)行的三種實(shí)現(xiàn)方式
為了實(shí)現(xiàn)Java的延遲執(zhí)行,常用的方法包括使用Thread。.sleep()使用Timer類,或使用ScheduledExecutorService接口的方法。
使用Thread.sleep()方法
Thread.sleep()方法是一種靜態(tài)方法,用于暫停執(zhí)行當(dāng)前線程一段時(shí)間,將CPU交給其他線程。使用這種方法實(shí)現(xiàn)延遲執(zhí)行非常簡單,只需將延遲時(shí)間作為參數(shù)傳入即可。
public class TestDelay {
public static void main(String[] args) {
System.out.println("Start: " + System.currentTimeMillis());
try {
Thread.sleep(5000); //延時(shí)5秒
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("End: " + System.currentTimeMillis());
}
}注意,Thread.sleep()方法可以被其它線程中斷,從而提前結(jié)束暫停。
使用Timer類。
Timer類可以用來安排一次執(zhí)行任務(wù)或重復(fù)固定執(zhí)行。通常需要配合TimerTask類使用Timer來實(shí)現(xiàn)延遲執(zhí)行。以下是一個(gè)簡單的例子:
import java.util.Timer;
import java.util.TimerTask;
public class TimerTaskTest {
public static void main(String[] args) {
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Task executed");
}
};
Timer timer = new Timer();
timer.schedule(task, 5000); // 在5秒內(nèi)執(zhí)行task
}
}使用ScheduledExecutorService接口接口
ScheduledExecutorService接口是ExecutorService的子接口,增加了對延遲執(zhí)行或定期執(zhí)行任務(wù)的支持。ScheduledExecutorService提供了錯(cuò)誤處理、結(jié)果獲取等更強(qiáng)大的功能。
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledExecutorServiceTest {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(new Runnable() {
@Override
public void run() {
System.out.println("Task executed");
}
}, 5, TimeUnit.SECONDS); // 五秒鐘后執(zhí)行任務(wù)
executor.shutdown();
}
}到此這篇關(guān)于Java延時(shí)執(zhí)行的三種實(shí)現(xiàn)方式的文章就介紹到這了,更多相關(guān)Java延時(shí)執(zhí)行內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java Swing組件單選框JRadioButton用法示例
這篇文章主要介紹了Java Swing組件單選框JRadioButton用法,結(jié)合具體實(shí)例形式分析了Swing單選框JRadioButton的使用方法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下2017-11-11
基于Beanutils.copyProperties()的用法及重寫提高效率
這篇文章主要介紹了Beanutils.copyProperties( )的用法及重寫提高效率的操作,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
關(guān)于Java中Object類的幾個(gè)方法示例
這篇文章主要給大家介紹了關(guān)于Java中Object類的幾個(gè)方法的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-05-05
SpringBoot集成slf4j2日志配置的實(shí)現(xiàn)示例
本文主要介紹了SpringBoot集成slf4j2日志配置的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-08-08
SpringBoot自定義定時(shí)任務(wù)的實(shí)現(xiàn)示例
本文主要介紹了SpringBoot自定義定時(shí)任務(wù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-05-05

