ScheduledExecutorService的用法

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TestScheduledExecutorService {

    private ScheduledExecutorService scheduleExector = null;

    public void doWork() {
        scheduleExector = Executors.newScheduledThreadPool(2);

        scheduleExector.scheduleAtFixedRate(new Runnable() {

            public void run() {
                System.out.println("每隔2秒鐘打印一次");
            }
        }, 2, 2, TimeUnit.SECONDS);

        scheduleExector.scheduleAtFixedRate(new Runnable() {

            public void run() {
                System.out.println("每隔3秒鐘打印一次");
            }
        }, 3, 3, TimeUnit.SECONDS);

    }

    public static void main(String args[]) {
        new TestScheduledExecutorService().doWork();
    }
}



scheduleAtFixedRate(Runnable command,
                                       long initialDelay,
                                       long period,
                                       TimeUnit unit)
創建並執行一個在給定初始延遲後首次啓用的定期操作,後續操作具有給定的週期;也就是將在 initialDelay 後開始執行,然後在 initialDelay+period 後執行,接着在 initialDelay + 2 * period 後執行,依此類推。如果任務的任何一個執行遇到異常,則後續執行都會被取消。否則,只能通過執行程序的取消或終止方法來終止該任務。如果此任務的任何一個執行要花費比其週期更長的時間,則將推遲後續執行,但不會同時執行。  

public interface ScheduledExecutorService
extends ExecutorService

一個 ExecutorService,可安排在給定的延遲後運行或定期執行的命令。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章