任务调度处理

任务调度有几种实现方式:java

  • Timer类的实现
private static final Long TwoSecond = 2 * 1000L;
    private static final Long ThreeSecond = 3 * 1000L;
    public static void main(String[] args) throws Exception {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                try {
                    System.out.printf("这是我这个任务处理的内容\n");
                } catch (Exception e) {}
            }
        };

        Timer timer = new Timer();
        timer.schedule(task, TwoSecond, ThreeSecond);
    }

结果入下:ide

  • Excutors.newScheduledThreadPool()实现
private static final Long TwoSecond = 2L;
    private static final Long ThreeSecond = 3L;
    public static void main(String[] args) throws Exception {
        ScheduledExecutorService service = Executors.newScheduledThreadPool(2);
        ScheduledFuture<String> futureList = service.schedule(
              new Sing("K歌之王"), TwoSecond, TimeUnit.SECONDS);
        ScheduledFuture<String> futureList2 = service.schedule(
              new Sing("淘汰"), ThreeSecond, TimeUnit.SECONDS);
        service.scheduleWithFixedDelay(
              new Sing2("简单爱"), ThreeSecond, TwoSecond, TimeUnit.SECONDS);
        System.out.println(futureList.get());
        System.out.println(futureList2.get());
    }

    public static class Sing implements Callable<String> {
        private String song = null;
        Sing(String song) {
            this.song = song;
        }
        @Override
        public String call() throws Exception {
            System.out.printf("singing:"+ song +"\n");
            return song;
        }
    }
    public static class Sing2 implements Runnable {
        private String song = null;
        Sing2(String song) {
            this.song = song;
        }
        @Override
        public void run()  {
            System.out.printf("run singing:"+ song +"\n");
        }
    }

结果以下:this

相关文章
相关标签/搜索