无法在java多线程中维护生产者任务的顺序 [英] Unable to maintain order of producer tasks in java multithreading

查看:116
本文介绍了无法在java多线程中维护生产者任务的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个多线程应用程序,其中有一个生产者尝试将元素添加到共享资源。我想维护生产者在共享资源中生成元素的顺序。

I am writing a multithreaded application where there a n producers who tries to add an element to the shared resource. I want to maintain the order in which producer produces the element in the shared resource.

例如,我的共享资源是SynchronizedQueue,P1,P2,P3,P4将以p1,p2,p3,p4的顺序产生新的元素那时P5生产者正在将其元素添加到队列中,因此P1,P2,P3,P4将等待锁定。一旦P5释放锁定,P1-4中的任何一个都将获得锁定,因此我们会松开元素的顺序。

For example my shared resource is a SynchronizedQueue and P1, P2, P3, P4 are going to produce a new elements in the order p1, p2, p3, p4 and during that time P5 producer is adding its element to the queue, so P1, P2, P3, P4 will be waiting for the lock. Once P5 releases the lock any one of the P1-4 will acquire the lock, so we loose the order of elements.

有没有办法维持元素的顺序谁在等锁?根据我的理解,这是不可能的,但我想检查是否可以通过编程方式实现。

Is there a way to maintain the order of elements who wait for a lock ? From my understanding it is not possible but I would like to check whether this can be achieved programmatically.

推荐答案

我能想到的一种方法是创建一个包装类, PriorityP 其中包含字段 int priority P值

One way I could think of would be to create a wrapper class, PriorityP which has the fields int priority and P value.

然后为每个线程分配一个优先级( int ),然后线程给出 PriorityP 的结果适当的优先级和价值。

Then you assign each thread a priority (int) and the thread gives as result a PriorityP with the appropriate priority and value.

现在,您可以使用 PriorityBlockingQueue 而不是 SynchronizedQueue ,并实施 比较者 PriorityP 类中的code> 界面。

Now, you can use a PriorityBlockingQueue instead of your SynchronizedQueue, and implement the Comparator interface in the PriorityP class.

当你这样做时,然后每当一个线程将其值输入队列时,它就会自动放入正确的位置。

When you do it like this, then whenever a thread enters his value into the queue, it is automatically put in the correct position.

这篇关于无法在java多线程中维护生产者任务的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆