(如何)我可能会“错过信号"吗?这个ConcurrentLinkedQueue和sleep()吗? [英] (How) can I possibly "miss a signal" with this ConcurrentLinkedQueue and sleep()?

查看:228
本文介绍了(如何)我可能会“错过信号"吗?这个ConcurrentLinkedQueue和sleep()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Java应用程序中,几个线程将数据放入一个队列中,另一个线程(仅一个)从该队列中获取对象并将其分派.

In my Java application, several threads put data in a queue from which another thread (just one) takes objects and dispatches them.

有时,使用方线程似乎没有注意到新项目已添加到队列中,因为指示轮询的日志消息不再出现.来自生产线程的日志消息表明这些项目确实已到达.谷歌搜索告诉我,这似乎被称为遗漏信号".由于我既不使用wait也不使用锁,所以我不确定这是否适用于我.

Occasionally, the consuming thread seems to not notice that new items have been added to the queue, as the log messages indicating a poll cease to appear. Log messages from the producing threads indicate that these items do indeed arrive. Googling some taught me that this seems to be known as "missed signal". Since I'm neither waiting nor using locks, I'm not sure if this applies to me.

真正令我困惑的是,当我中断使用者线程时,它会处理队列中的所有项目,然后再次保持沉默,而不会退出.

What really puzzles me is that when I interrupt the consumer thread, it processes all items in the queue and then stays silent again, without ever exiting.

这是使用者线程的主循环,生产者线程的工作类似于从套接字读取数据,它们唯一的共同之处在于它们在使用者进行轮询的队列上使用add().

Here's the main loop of the consumer thread, the producer threads do stuff like reading from sockets and their only common thing is that they use add() on the queue from which the consumer is polling.

public class FieldFrontService
{
    // ...

    private ConcurrentLinkedQueue<Transmission> _qRec;

    // ...

    private Runnable _createReceptionist()
    {
        return new Runnable() {
            @Override
            public void run()
            {
                while (!Thread.currentThread().isInterrupted()) {
                    Transmission tx = FieldFrontService.this._qRec.poll();
                    if (null == tx) {
                        try {
                            Thread.sleep(250);
                        } catch (InterruptedException e) {
                            break;
                        }
                    } else {
                        FieldFrontService.this._receiveTransmission(tx);
                    }
                }
            }
        }

    // ...
}

推荐答案

也许最好使用结合了线程池和队列的ExecutorService.也可以. ;)

Perhaps you are better off using an ExecutorService which combines a Thread pool and a Queue. Also it works. ;)

public class FieldFrontService {
    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    void receiveTransmission(final Transmission tx) {
        executor.execute(new Runnable() {
            public void run() {
                FieldFrontService.this._receiveTransmission(tx);
            }
        });
    }
}

这篇关于(如何)我可能会“错过信号"吗?这个ConcurrentLinkedQueue和sleep()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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