【问题标题】:Threads and Interrupts: Continue or exit?线程和中断:继续还是退出?
【发布时间】:2013-08-25 17:43:07
【问题描述】:

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

这里是有问题的代码:

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 android multithreading interrupt


    【解决方案1】:

    我想答案取决于你为什么被打断?通常线程被中断是因为其他一些进程/线程试图取消或杀死它。在这些情况下,停止是合适的。

    也许当被打断时,你会发出所有剩余的消息而不接受新消息?

    【讨论】:

    • 我的印象是中断并不总是由程序员控制,我必须处理来自系统的中断,因为其他地方需要 OS 线程。这不是真的吗?
    • 我认为操作系统上下文切换不会引发中断,因此您不必担心这一点。这个 SO 问题比我能解释的更好:stackoverflow.com/questions/2126997/…
    • 所以我唯一能获得中断的情况是我自己调用interrupt() 或者将线程传递给另一个调用它的方法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多