Java ScheduledFuture获取List

时间:2018-01-12 08:52:03

标签: java multithreading scheduling futuretask

此代码总是返回10.我认为接收所有功能列表的问题。当变量限制等于5时,我需要解析每个功能并停止执行调度程序。我该怎么办?

static int limit = 0;
static final int testNum = 10;

static ScheduledExecutorService scheduler;
public static void main(String[] args) {
    scheduler = Executors
            .newScheduledThreadPool(5);
    ScheduledFuture<Integer> future = scheduler.schedule(new ScheduledPrinter(), 10, TimeUnit.SECONDS);
    try {
        while (true) {
            System.out.println(future.get());
            if(future.get() != testNum){
                return;
            }
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}
private static class ScheduledPrinter implements Callable<Integer> {
    public Integer call() throws Exception {
        limit++;
        if(limit==5) {
            scheduler.shutdown();
            return limit;
        }
        return testNum;
    }
}

2 个答案:

答案 0 :(得分:1)

让我们看看这里发生了什么。 scheduler.schedule(new ScheduledPrinter(), 10, TimeUnit.SECONDS)仅运行一次ScheduledPrinter.call()Here是API文档。

你想要的可能是scheduleAtFixedRate。这需要Runnable而不是可调用,因此代码看起来像这样:

static volatile int limit = 0; // make it volatile because of *possible* multithreaded access
                               // an AtomicInteger would do too
static final int testNum = 10;

static ScheduledExecutorService scheduler;

public static void main(String[] args) {
    scheduler = Executors
            .newScheduledThreadPool(5);
    // discarding the future. No need to use it here.
    ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(new ScheduledPrinter(), 10L, 10L, TimeUnit.SECONDS);
}

/** Printing and counting happens here **/
private static class ScheduledPrinter implements Runnable {

    @Override
    public void run() {
        limit++;
        if(limit==5) {
            scheduler.shutdown();
            printNum(limit);
        } else {
            printNum(testNum);
        }
    }

    private void printNum(int num) {
        System.out.println(num);
    }
}

更新

OP询问如何从Runnable.run()方法返回值?不幸的是,这是不可能的。我们必须在定期运行和返回值之间进行选择,因为ScheduledExecutorService不能同时执行这两种操作。

仍有可能从Runnable中获取一个值。我们必须分享一个参考。这是一个基本的方法:

    final Queue<Integer> numsPrinted = new ConcurrentLinkedQueue<>(); // a concurrent collection
    ScheduledFuture<?> future = scheduler.scheduleWithFixedDelay( // using scheduleWithFixedDelay because probably this is what you want
            new ScheduledPrinter(numsPrinted), // passing the reference
            10L, 10L, TimeUnit.SECONDS);
    try {
        future.isDone();
        Object obj = future.get(80, TimeUnit.SECONDS); // blocks until 80 secs or until the task is done
        System.out.println(obj);
        System.out.println(Arrays.toString(numsPrinted.toArray()));
    } catch (TimeoutException e) {
        System.out.println(Arrays.toString(numsPrinted.toArray()));
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    } 

ScheduledPrinter现在看起来像这样:

private static class ScheduledPrinter implements Runnable {

    private final Queue<Integer> numsPrinted;

    public ScheduledPrinter(Queue<Integer> numsPrinted) {
        this.numsPrinted = numsPrinted; // storing the reference
    }

    @Override
    public void run() {
        limit++;
        if(limit==5) {
            //scheduler.awaitTermination(timeout, unit)
            scheduler.shutdown();
            storeAndPrintNum(limit);
        } else {
            storeAndPrintNum(testNum);
        }
    }

    private void storeAndPrintNum(int num) {
        numsPrinted.add(num); // using the reference
        System.out.println(num);
    }
}

答案 1 :(得分:0)

方法ScheduledPrinter.call()只被调用一次,而在while循环中,您总是返回计算一次的值。因此,限制永远不会增加,并且永远不会调用关闭。所以我认为你需要改变逻辑,或者运行更多的线程。