繁体   English   中英

在线程中断之后将线程重新连接到主线程有什么意义?

[英]what is the point of rejoining the thread to the main-thread after the thread has been interrupted?

我从Java教程oracle看了下面的代码。 我只是想知道在中断之后将线程重新连接到主线程有什么意义?

if(((System.currentTimeMillis() - startTime) > patience) && t.isAlive()){
    threadMessage("tired of waiting");
    t.interrupt();
    t.join();

}

我从if语句中删除了t.join() ,并且看起来一切都一样。 那么,为什么编写代码的方式呢?

public class SimpleThreads {


    static void threadMessage(String message){
        String threadName = Thread.currentThread().getName();
        System.out.format("%s: %s%n", threadName, message);
    }

    private static class MessageLoop implements Runnable {

        @Override 
        public void run (){
            String[] importantInfo = { "dog", "cat", "mice"};

            try {
                for(int i = 0; i < importantInfo.length; i++){
                    Thread.sleep(4000);
                    threadMessage(importantInfo[i]);
                }
            } catch (InterruptedException e){
                threadMessage("i wasn't done!");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        long patience = 10000;

        threadMessage("starting MessageLoop thread");
        long startTime = System.currentTimeMillis();
        Thread t = new Thread(new MessageLoop());
        t.start();

        threadMessage("waiting for MessageLoop thread to finish");
        while(t.isAlive()){
            threadMessage("still waiting...");
            t.join(1000);

            if(((System.currentTimeMillis() - startTime) > patience) && t.isAlive()){
                threadMessage("tired of waiting");
                t.interrupt();
                t.join();

            }
        }
        threadMessage("finally");
    }


}

你打电话时

t.join(1000);

Java不会尽一切努力通知相应的线程您希望它在1000毫秒内完成。 如果该线程正在阻止IO或正在像您一样正在休眠,它将继续这样做。

在这里,本教程演示了一种更简洁的关闭模式。 他们首先interrupt线程,该线程将从sleep唤醒(如果正在执行),并最终终止。 然后,他们调用join()等待该终止。

他们本可以省略join但根据线程( daemon? )的类型及其用途,可能会使应用程序处于不可预测的状态。


重要的是要重复说中断是一种协作的努力。 如果要彻底终止线程,则必须公开(正确记录)适当的中断模式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM