在Java线程中interrupt()之后调用join()

问题描述 投票:0回答:1

我正在学习 Thread Java,并且遵循 official docs java

上的教程

此示例结合了各种方法:

join()
sleep()
interrupt()
和 ,
start()

public class SimpleThread {
    // Display a message, preceded by
    // the name of the current thread
    static void threadMessage(String message) {
        String threadName = Thread.currentThread().getName();
        System.out.format("%s: %s%n", threadName, message);
    }

    private static class MessageLoop implements Runnable {
        public void run() {
            String importantInfo[] = {
                    "Mares eat oats",
                    "Does eat oats",
                    "Little lambs eat ivy",
                    "A kid will eat ivy too"
            };

            try {
                for (int i = 0;
                     i < importantInfo.length;
                     i++) {
                    // Pause for 4 seconds
                    Thread.sleep(4000);
                    // Print a message
                    threadMessage(importantInfo[i]);
                }
            } catch (InterruptedException e) {
                threadMessage("I wasn't done!");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // Delay, in milliseconds before
        // we interrupt MessageLoop
        // thread (default 10s).
        long patience = 1000 * 10;

        threadMessage("Starting MessageLoop thread");
        long startTime = System.currentTimeMillis();

        Thread t = new Thread(new MessageLoop(), "MessageLoop");
        t.start();
        threadMessage("Waiting for MessageLoop thread to finish");

        while (t.isAlive()) {
            threadMessage("Still waiting...");
            t.join(16000);

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

                t.join();
            }
        }
        threadMessage("Finally!");
    }
}

作者为什么在

join()
之后使用
interrupt()

这样做的目的是什么?因为我尝试评论它,但没有任何改变。

java java-threads
1个回答
0
投票

在线程上调用中断会通知线程终止,但不会强制线程终止。所以线程可能仍在运行。调用 join 将强制调用线程等待,直到被中断的线程完成,或者本身被中断。

在您的线程中,大部分等待是由 Thread.sleep() 引起的。当您调用中断时,当前或下一个睡眠调用将以中断异常结束。这意味着被中断的工作线程将很快结束。在这种情况下,调用 join 可能没有必要,因为线程终止得如此之快。

© www.soinside.com 2019 - 2024. All rights reserved.