java - 线程和中断: Continue or exit?

标签 java android multithreading interrupt

我能找到的官方文档和论坛帖子对此非常模糊。他们说,由程序员决定在被中断后是否继续或退出,但我找不到任何可以保证其中之一的条件的文档。

这是有问题的代码:

private final LinkedBlockingQueue<Message> messageQueue = new LinkedBlockingQueue<Message>();


// The sender argument is an enum describing who sent the message: the user, the app, or the person on the other end.
public void sendMessage(String address, String message, Sender sender) {
    messageQueue.offer(Message.create(address, message, sender));
    startSenderThread();
}

private Thread senderThread;

private void startSenderThread(){

    if(senderThread == null || !senderThread.isAlive()){
        senderThread = new Thread(){
            @Override
            public void run() {
                loopSendMessage();
            }
        };

        senderThread.start();
    }
}

private void loopSendMessage(){
    Message queuedMessage;

    // Should this condition simply be `true` instead?
    while(!Thread.interrupted()){
        try {
            queuedMessage = messageQueue.poll(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            EasyLog.e(this, "SenderThread interrupted while polling.", e);
            continue;
        }
        if(queuedMessage != null)
            sendOrQueueMessage(queuedMessage);
        else
            break;
    }
}

// Queue in this context means storing the message in the database
// so it can be sent later.
private void sendOrQueueMessage(Message message){
    //Irrelevant code omitted.
}

sendMessage() 方法可以随时从任何线程调用。它发布一条新消息以发送到消息队列,并启动发送者线程(如果该线程未运行)。发送者线程通过超时轮询队列,并处理消息。如果队列中没有更多消息,则线程退出。

它适用于自动处理 SMS 消息的 Android 应用程序。这是一个处理出站消息的类,决定是否立即发送它们或保存它们以供稍后发送,因为 Android 有内部 100 条消息/小时的限制,只能通过 root 和访问设置数据库来更改。

用户或应用程序本身可以同时从应用程序的不同部分发送消息。决定何时排队等待需要同步处理,以避免需要原子消息计数。

我想优雅地处理中断,但如果有更多消息要发送,我不想停止发送消息。关于线程的 Java 文档说大多数方法在被中断后只是简单地返回,但这会在队列中留下未发送的消息。

有人可以推荐一个行动方案吗?

最佳答案

我想答案取决于你被打扰的原因?线程经常被中断,因为其他一些进程/线程试图取消或终止它。在这些情况下,停止是适当的。

也许当中断时,您会发送所有剩余的消息并且不接受新的消息?

关于java - 线程和中断: Continue or exit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18389839/

相关文章:

android - 如何解决 "Google Play will block publishing of any new apps or updates that use an unsafe implementation of HostnameVerifier"?

javascript - Titanium 双击和单击事件处理程序

android - 带下划线的变量

multithreading - rust tokio::spawn 在 mutexguard 之后等待

python - 如何跟踪多线程软件?

java - 是否可以向我没有源代码的类添加断点?

java - 在设计系统的其他部分之前开发原型(prototype) GUI 是否明智?

java - 如何使用 couchbase SearchQuery 查询两组参数

java - org.json.JSONException : No value for custom

c# - 下面的 VB.NET 实现随机线程安全吗?