主线程中执行scheduledexecutorservice的scheduled方法 ,两个线程执行顺序

主线程中执行scheduledexecutorservice的scheduled方法 ,主线程会等代码 如果不会等待 怎么做能让其等待

阅读 3.1k
1 个回答

我测试验证了下,主线程会等待,因为ScheduledExecutorService没有被shutdown,你的需求是什么?如果你希望执行结束后结束进行,那么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();
        }
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题