Android开发

线程池示例(二)Executors.newScheduledTh

2019-03-31  本文已影响0人  乌鲁木齐001号程序员

示例1 - 延迟执行

import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ThreadPoolExample4 {

    public static void main(String[] args) {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(int corePoolSize);

        scheduledExecutorService.schedule(new Runnable() {
            @Override
            public void run() {
                log.warn("schedule run");
            }
        }, 3, TimeUnit.SECONDS);
    }

}

输出:

17:40:36.288 [pool-1-thread-1] WARN com.example.concurrency.example.threadPool.ThreadPoolExample4 - schedule run

示例2 - 周期性执行

import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ThreadPoolExample4 {

    public static void main(String[] args) {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                log.warn("schedule run");
            }
        }, 1, 3, TimeUnit.SECONDS);
    }

}

输出:

17:43:28.481 [pool-1-thread-1] WARN com.example.concurrency.example.threadPool.ThreadPoolExample4 - schedule run
17:43:31.478 [pool-1-thread-1] WARN com.example.concurrency.example.threadPool.ThreadPoolExample4 - schedule run
17:43:34.478 [pool-1-thread-1] WARN com.example.concurrency.example.threadPool.ThreadPoolExample4 - schedule run
17:43:37.478 [pool-1-thread-1] WARN com.example.concurrency.example.threadPool.ThreadPoolExample4 - schedule run

示例3 - 用Timer周期性执行

import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ThreadPoolExample4 {

    public static void main(String[] args) {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                log.warn("timer run");
            }
        }, new Date(), 5 * 1000);
    }
}

输出:

17:48:13.543 [Timer-0] WARN com.example.concurrency.example.threadPool.ThreadPoolExample4 - timer run
17:48:18.540 [Timer-0] WARN com.example.concurrency.example.threadPool.ThreadPoolExample4 - timer run
17:48:23.541 [Timer-0] WARN com.example.concurrency.example.threadPool.ThreadPoolExample4 - timer run

上一篇下一篇

猜你喜欢

热点阅读