import java.util.Timer;
import java.util.TimerTask;
/**
* @description: 測(cè)試使用單線程定時(shí)器
*/
public class TestTimer {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("test...");
}
}, 1000L, 1000L);
}
}
package com.spiov.cloud.test;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @description: 測(cè)試使用線程池定時(shí)器
*/
public class TestScheduled {
public static void main(String[] args) throws InterruptedException {
//創(chuàng)建大小為5的線程池
ScheduledExecutorService scheduledPool = Executors.newScheduledThreadPool(5);
Task worker = new Task("task");
// 只執(zhí)行一次
// scheduledPool.schedule(worker, 5, TimeUnit.SECONDS);
// 周期性執(zhí)行,每1秒執(zhí)行一次
scheduledPool.scheduleAtFixedRate(worker, 0,1, TimeUnit.SECONDS);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
System.out.println("Shutting down executor...");
// 關(guān)閉線程池
scheduledPool.shutdown();
boolean isDone;
// 等待線程池終止
do {
isDone = scheduledPool.awaitTermination(1, TimeUnit.DAYS);
System.out.println("awaitTermination...");
} while(!isDone);
System.out.println("Finished all threads");
}
}
class Task implements Runnable {
private String name;
public Task(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println("threadName = "+Thread.currentThread().getName()+",taskName = " + name + ", startTime = " + LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE));
}
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。