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