单线程执行任务,无需排队进一步的请求

2023-12-22

我需要异步执行任务,同时丢弃任何进一步的请求,直到任务完成。

同步方法只是将任务排队并且不会跳过。我最初想使用 SingleThreadExecutor 但它也会对任务进行排队。然后,我查看了 ThreadPoolExecutor,但它读取队列来获取要执行的任务,因此将执行一个任务,并且至少有一个任务排队(其他任务可以使用 ThreadPoolExecutor.DiscardPolicy 丢弃)。

我唯一能想到的就是使用信号量来阻塞队列。我用下面的例子来展示我想要实现的目标。有没有更简单的方法?我错过了一些明显的事情吗?

import java.util.concurrent.*;

public class ThreadPoolTester {
    private static ExecutorService executor = Executors.newSingleThreadExecutor();
    private static Semaphore processEntry = new Semaphore(1);

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 20; i++) {
            kickOffEntry(i);

            Thread.sleep(200);
        }

        executor.shutdown();
    }

    private static void kickOffEntry(final int index) {
        if (!processEntry.tryAcquire()) return;
        executor.
            submit(
                new Callable<Void>() {
                    public Void call() throws InterruptedException {
                        try {
                            System.out.println("start " + index);
                            Thread.sleep(1000); // pretend to do work
                            System.out.println("stop " + index);
                            return null;

                        } finally {
                            processEntry.release();
                        }
                    }
                }
            );
    }
}

样本输出

start 0
stop 0
start 5
stop 5
start 10
stop 10
start 15
stop 15

采用 axtavt 的答案并转换上面的示例给出了以下更简单的解决方案。

import java.util.concurrent.*;

public class SyncQueueTester {
    private static ExecutorService executor = new ThreadPoolExecutor(1, 1, 
            1000, TimeUnit.SECONDS, 
            new SynchronousQueue<Runnable>(),
            new ThreadPoolExecutor.DiscardPolicy());

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 20; i++) {
            kickOffEntry(i);

            Thread.sleep(200);
        }

        executor.shutdown();
    }

    private static void kickOffEntry(final int index) {
        executor.
            submit(
                new Callable<Void>() {
                    public Void call() throws InterruptedException {
                        System.out.println("start " + index);
                        Thread.sleep(1000); // pretend to do work
                        System.out.println("stop " + index);
                        return null;
                    }
                }
            );
    }
}

看起来像是执行者支持的SynchronousQueue与所需的政策做你想做的事:

executor = new ThreadPoolExecutor(
    1, 1, 
    1000, TimeUnit.SECONDS, 
    new SynchronousQueue<Runnable>(),
    new ThreadPoolExecutor.DiscardPolicy());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

单线程执行任务,无需排队进一步的请求 的相关文章

随机推荐