Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Java中的生产者和消费者防止有界执行器服务中可能出现的死锁情况_Java_Multithreading_Concurrency_Deadlock - Fatal编程技术网

使用Java中的生产者和消费者防止有界执行器服务中可能出现的死锁情况

使用Java中的生产者和消费者防止有界执行器服务中可能出现的死锁情况,java,multithreading,concurrency,deadlock,Java,Multithreading,Concurrency,Deadlock,考虑以下示例代码:(我简化了很多类,因此它们更易于阅读) 制作人 消费者从队列中提取号码并将其打印到指定的可追加的。可以通过Thread.interrupt()取消 起始代码 class ProducerConsumerStarter { /*请注意,这是一个固定大小(例如有界)的executor服务*/ 私有静态最终执行器服务=Executors.newFixedThreadPool(8); 公共静态列表startIntegerProducerConsumer(int生产者、int消费者) {

考虑以下示例代码:(我简化了很多类,因此它们更易于阅读)

制作人 消费者从队列中提取号码并将其打印到指定的可追加的
。可以通过
Thread.interrupt()
取消

起始代码
class ProducerConsumerStarter
{
/*请注意,这是一个固定大小(例如有界)的executor服务*/
私有静态最终执行器服务=Executors.newFixedThreadPool(8);
公共静态列表startIntegerProducerConsumer(int生产者、int消费者)
{
List callables=new ArrayList();
BlockingQueue commonQueue=新的ArrayBlockingQueue(16);
for(int i=0;i
此实用程序方法将任务提交给有界执行器服务(按顺序-首先是所有生产者,然后是所有消费者)

失败的客户端代码
公共类失败示例{
@org.junit.Test
public void deadlockApplication()引发异常
{
列表期货=生产商消费者开始。开始生产商消费者(10,10);
for(未来:未来)
{
System.out.println(“获得未来”);
future.get();
}
}
}
此示例代码通过死锁此并发程序和启动代码的任何其他未来调用方而使其失败


问题是:我如何既能防止我的应用程序在高负载下产生大量线程(我希望任务排成队列),又能仅仅通过执行器被生产者污染来防止死锁

即使这个样本在100%的时间内明显失败,考虑一个并发程序,在一个不吉利的情况下,完全填充有限量的执行器和生产者——你将遇到相同的一般问题。

< P>什么是死锁? 死锁描述两个或多个线程被阻塞的情况 永远,等待彼此

因此,当第一个线程持有monitor1并试图获取monitor2时,死锁就会发生,而第二个线程持有monitor2并试图获取monitor1。
代码中没有死锁,因为没有两个或更多线程。。彼此等待
。队列中有生产者在等待空间,没有消费者,因为由于执行者的线程数,他们没有被调度

另外,“失败的客户端代码”将始终阻止线程,即使使用
startIntegerProducerConsumer(1,1)

此循环将获取已完成任务的结果,并取消未完成任务

@vanOekel是正确的,最好有两个线程池,一个用于消费者,另一个用于生产者。
像这样

class ProducerConsumerStarter
{
    private static final ExecutorService CONSUMERS = Executors.newFixedThreadPool(8); 
    private static final ExecutorService PRODUCERS = Executors.newFixedThreadPool(8); 

    public static List<Future<Void>> startIntegerProducerConsumer(int producers, int consumers) {
        ...
    }
}
然后开始使用
scheduleWithFixedDelay(producer,1,1,TimeUnit.SECONDS)
将生产者提交到中。这一变化将有助于保持生产商运行,而不会相互阻塞。但它也会稍微改变应用程序的语义。
您可以将
ScheduledExecutorService
(对于生产者)初始化为类变量。唯一的不便之处在于,您必须将
startIntegerProducerConsumer(int生产者、int消费者)
方法的返回类型更改为
List
return in
scheduleWithFixedDelay(..)
的类型仍然是
Future
。 如果可能的话,您也可以对使用者执行相同的操作,在使用新生成的数字期间,最大延迟(相当于
延迟
(传递到
scheduleWithFixedDelay()
)对您来说是合适的


我希望我的回答能有所帮助。

使用两个executor服务,一个用于生产者,一个用于消费者?此外,线程池有一个无限的队列,因此使用固定大小的线程池,您不会产生大量的线程,具有执行任务的队列将只增长。@ VANOEKEL与两个执行器:考虑10对消费者+生产者和两个执行者,每个限制在10个线程中。如果任务是从不同线程执行的,这也意味着生产者1-10被执行,消费者11-20被执行。(由于VM的代码重新排序)?或者不是(请实际回答)?实际上,应用程序可能会锁定,因为固定大小的executor服务的线程永远不会退出,因为没有消费者在运行(而不是因为任务队列已满)。它不是“VM的代码重新排序”不会改变元素添加到列表中的顺序。@vanOekel好吧,那听起来是个不错的解决方案。我很高兴你能给出答案。哦,是的,你说得对,
deadlockApplication()
never exits(永不退出)-我应该指定我只是想证明他们永远无法退出,我还忘了让制作人自己退出……哎呀。如果我没有忘记这两个,它应该证明制作人将永远等待。关于预定执行者,你是对的,重点只是确保应用程序不会在瞬间终止。谢谢您的回答!
class NumberConsumer implements Callable<Void>
{
    private final BlockingQueue<? extends Number> queue;
    private final Appendable target;

    /* Boilerplate constructor... */

    @Override
    public Void call() throws IOException
    {
        while (!Thread.interrupted())
        {
            try {
                target.append(queue.take().toString());
            } catch (InterruptedException e)
            {
                Thread.currentThread().interrupt();
                break;
            }
        }
        return null;
    }
}
class ProducerConsumerStarter
{
    /* Notice this is a fixed size (e.g. bounded) executor service */
    private static final ExecutorService SERVICE = Executors.newFixedThreadPool(8);

    public static List<Future<Void>> startIntegerProducerConsumer(int producers, int consumers)
    {
        List<Callable<Void>> callables = new ArrayList<>();
        BlockingQueue<Integer> commonQueue = new ArrayBlockingQueue<>(16);
        for (int i = 0; i < producers; i++)
        {
            callables.add(new RandomIntegerProducer(commonQueue, new Random()));
        }
        for (int i = 0; i < consumers; i++)
        {
            callables.add(new NumberConsumer(commonQueue, System.out));
        }
        // Submit them all (in order)
        return callables.stream().map(SERVICE::submit).collect(Collectors.toList());
    }
}
public class FailingExaple {
    @org.junit.Test
    public void deadlockApplication() throws Exception
    {
        List<Future<Void>> futures = ProducerConsumerStarter.startIntegerProducerConsumer(10, 10);
        for (Future<Void> future : futures)
        {
            System.out.println("Getting future");
            future.get();
        }
    }
}
public class FailingExaple {
    @org.junit.Test
    public void deadlockApplication() throws Exception
    {
        List<Future<Void>> futures = ProducerConsumerStarter.startIntegerProducerConsumer(10, 10);
        for (Future<Void> future : futures)
        {
            System.out.println("Getting future");
            future.get();
        }
    }
}
for (Future<Void> future : futures)
{
    if (future.isDone()) {
        try {
            System.out.println("Getting future");
            future.get();
        } catch (CancellationException ce) {

        } catch (ExecutionException ee) {

        }
    } else {
        System.out.println("The future is not done, cancelling it");
        if (future.cancel(true)) {
            System.out.println("task was cancelled");
        } else {
            //handle case when FutureTask#cancel(boolean mayInterruptIfRunning) wasn't cancelled
        }
    }
}
class ProducerConsumerStarter
{
    private static final ExecutorService CONSUMERS = Executors.newFixedThreadPool(8); 
    private static final ExecutorService PRODUCERS = Executors.newFixedThreadPool(8); 

    public static List<Future<Void>> startIntegerProducerConsumer(int producers, int consumers) {
        ...
    }
}
class RandomIntegerProducer implements Runnable
{
    private final BlockingQueue<? super Integer> queue;
    private final Random random;
    ...
    @Override
    public void run()
    {
        queue.offer(random.nextInt());
    }
}