ExecutorService 和 AtomicInteger : Rejected

我希望 atomicInteger 的值为 100 然后程序终止


 public static void main(String[] args) throws InterruptedException {

        ExecutorService executor = Executors.newSingleThreadExecutor();

        AtomicInteger atomicInteger = new AtomicInteger(0);

        do {

            executor.submit(() -> {

                System.out.println(atomicInteger.getAndAdd(10));

                if (atomicInteger.get() == 100) {

                    //executor.shutdownNown();

                }

            });

        } while (true);

    }

我有错误


Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@1d8d10a rejected from java.util.concurrent.ThreadPoolExecutor@9e54c2[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 10]

    at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)

    at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)

    at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1374)

    at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)

    at java.util.concurrent.Executors$DelegatedExecutorService.submit(Executors.java:678)

我应该如何实现它。


大话西游666
浏览 152回答 2
2回答

慕妹3146593

这里不需要使用 AtomicInteger,因为您的 Runnable lambda 函数调用保证按顺序执行(通过新的 SingleThreadExecutor)。此外,您的 Runnable lambda 代码需要任何时间来执行(例如 2 毫秒),您的主循环将排队超过 10 个任务以达到您的限制。如果您在 Runnable lambda 函数中添加 2ms 睡眠,您可以看到这种情况发生,并且还在您的 do/while 循环中添加一个计数器,并在最后打印出计数器的值以查看您排队的 Runnable 实例的数量。假设您希望使用并发线程测试此代码,则需要用 newFixedThreadPool 替换对 newSingleThreadPool 的调用。当使用并发线程时,您的代码采用的方法是有问题的。在下面的代码中,我切换到 newFixedThreadPool,添加了一个计数器,因此我们可以看到有多少任务排队,并添加到 Runnable lambda 函数中的短暂停顿,仅表示少量工作。当我执行这个程序时, atomicInteger 变得大于 13000 并且程序崩溃了java.lang.OutOfMemoryError: GC 开销限制超出那是因为,无论它的当前值如何,您的可运行函数总是将 10 添加到 atomicInteger 。而且,代码排队的任务比它需要的多。这是说明问题的具有这些小更改的代码。public static void main(String[] args) {&nbsp; &nbsp; ExecutorService executor = Executors.newFixedThreadPool(3);&nbsp; &nbsp; AtomicInteger atomicInteger = new AtomicInteger(0);&nbsp; &nbsp; int i=0;&nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; executor.submit(() -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pause(2); // simulates some small amount of work.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("atomicInt="+atomicInteger.getAndAdd(10));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pause(2); // simulates some small amount of work.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (atomicInteger.get() == 100) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("executor.shutdownNow()");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.flush();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; executor.shutdownNow();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; if (atomicInteger.get() == 100) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } while (true);&nbsp; &nbsp; System.out.println("final atomicInt="+atomicInteger.get());&nbsp; &nbsp; System.out.println("final tasks queued="+i);}public static void pause(long millis) {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; Thread.sleep(millis);&nbsp; &nbsp; } catch (InterruptedException ex) {&nbsp; &nbsp; }}这是一个修复并发问题并将执行程序管理移出它不真正属于的工作线程的版本:private static int LIMIT = 100;private static int INCREMENT = 10;public static void main(String[] args) {&nbsp; &nbsp; ExecutorService executor = Executors.newFixedThreadPool(2);&nbsp; &nbsp; AtomicInteger atomicInteger = new AtomicInteger(0);&nbsp; &nbsp; for (int i=0; i < LIMIT/INCREMENT; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; executor.submit(() -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pause(2);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("atomicInt=" + atomicInteger.getAndAdd(INCREMENT));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.flush();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pause(2);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; &nbsp; executor.shutdown();&nbsp; &nbsp; while (!executor.isTerminated()) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Executor not yet terminated");&nbsp; &nbsp; &nbsp; &nbsp; System.out.flush();&nbsp; &nbsp; &nbsp; &nbsp; pause(4);&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println("final atomicInt=" + atomicInteger.get());}public static void pause(long millis) {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; Thread.sleep(millis);&nbsp; &nbsp; } catch (InterruptedException ex) {&nbsp; &nbsp; }}

扬帆大鱼

您应该只更改您的 while 循环以检查您需要的条件并在此之后关闭执行程序
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java