標籤:線程池 util 並發 stat sleep imp 任務 err cat
/**
* 普通thread
* 這是最常見的,建立一個thread,然後讓它在while迴圈裡一直運行著,
* 通過sleep方法來達到定時任務的效果。這樣可以快速簡單的實現,代碼如下
*/
public class Task1 {
public static void main(String[] args) {
// run in a second
final long timeInterval = 1000;
Runnable runnable = new Runnable() {
public void run() {
while (true) {
// ------- code for task to run
System.out.println("Hello !!");
// ------- ends here
try {
Thread.sleep(timeInterval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
}
import java.util.Timer;
import java.util.TimerTask;
/**
*
* 於第一種方式相比,優勢 1>當啟動和取消任務時可以控制 2>第一次執行任務時可以指定你想要的delay時間
*
* 在實現時,Timer類可以調度任務,TimerTask則是通過在run()方法裡實現具體任務。 Timer執行個體可以調度多任務,它是安全執行緒的。
* 當Timer的構造器被調用時,它建立了一個線程,這個線程可以用來調度任務。 下面是代碼
*/
public class Task2 {
public static void main(String[] args) {
TimerTask task = new TimerTask() {
@Override
public void run() {
// task to run goes here
System.out.println("Hello !!!");
}
};
Timer timer = new Timer();
long delay = 0;
long intevalPeriod = 1 * 1000;
// schedules the task to be run in an interval
timer.scheduleAtFixedRate(task, delay, intevalPeriod);
} // end of main
}
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* ScheduledExecutorService是從Java SE5的java.util.concurrent裡做為並發工具類被引進的,這是最理想的定時任務實現方式。
* 相比於上兩個方法,它有以下好處:
* 1>相比於Timer的單線程,它是通過線程池的方式來執行任務的
* 2>可以很靈活的去設定第一次執行任務delay時間
* 3>提供了良好的約定,以便設定執行的時間間隔
*
* 下面是實現代碼,我們通過ScheduledExecutorService#scheduleAtFixedRate展示這個例子,通過代碼裡參數的控制,首次執行加了delay時間。
*/
public class Task3 {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
public void run() {
// task to run goes here
System.out.println("Hello !!");
}
};
ScheduledExecutorService service = Executors
.newSingleThreadScheduledExecutor();
// 第二個參數為首次執行的延時時間,第三個參數為定時執行的間隔時間
service.scheduleAtFixedRate(runnable, 10, 1, TimeUnit.SECONDS);
}
}
java定時任務的三種方式