鍍金池/ 問答/Java  Linux/ 主線程中執(zhí)行scheduledexecutorservice的scheduled

主線程中執(zhí)行scheduledexecutorservice的scheduled方法 ,兩個線程執(zhí)行順序

主線程中執(zhí)行scheduledexecutorservice的scheduled方法 ,主線程會等代碼 如果不會等待 怎么做能讓其等待

回答
編輯回答
尕筱澄

我測試驗證了下,主線程會等待,因為ScheduledExecutorService沒有被shutdown,你的需求是什么?如果你希望執(zhí)行結束后結束進行,那么shutdown即可。

你參考下以下例子:

public static void main(String[] args) throws IOException {
        Object agentInfo = null;
        Integer samplingInterval = 30;

        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(10);
        executorService.schedule(new WatchAgent(agentInfo), 1, TimeUnit.SECONDS);
//        executorService.scheduleAtFixedRate(new WatchAgent(agentInfo), 0, samplingInterval, TimeUnit.SECONDS);
        System.err.println("FINISH");
}

static class WatchAgent implements Runnable {

    public WatchAgent(Object info){

    }

    public void run(){
        try{
            System.out.println("Running " + this.hashCode() + " - started on/at " + (new Date()));
            Thread.sleep(6000);
            System.out.println("Running " + this.hashCode() + " - finished on/at " + (new Date()));
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}
2018年5月14日 11:40