【问题标题】:Thread is not executing in spite of using method join尽管使用了方法连接,但线程没有执行
【发布时间】:2016-03-21 22:43:05
【问题描述】:

我不太明白为什么我会得到这段代码的输出:

public class Example {

    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[] = {
                "Line 1",
                "Line 2",
                "Line 3",
                "Line 4"
            };
            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) {
                ;
            }
        }
    }

    public static void main(String args[]) throws InterruptedException {


        threadMessage("Starting MessageLoop thread");
        Thread t = new Thread(new MessageLoop());
        t.start();

        threadMessage("Waiting for MessageLoop thread to finish");

        while (t.isAlive()) {
            threadMessage("Still waiting...");
            // Wait maximum of 1 second
            // for MessageLoop thread
            // to finish.
            t.join(1000);
        }
        threadMessage("Finally!");
    }
}

输出:

main: 启动 MessageLoop 线程 main:等待 MessageLoop 线程完成 主:还在等…… 主:还在等…… 主:还在等…… 主:还在等…… 主:还在等…… 线程 0:第 1 行 主:还在等…… 主:还在等…… 主:还在等…… 主:还在等…… 线程 0:第 2 行 主:还在等…… 主:还在等…… 主:还在等…… 线程 0:第 3 行 主:还在等…… 主:还在等…… 主:还在等…… 主:还在等…… 线程 0:第 4 行 主:终于!

如果我在循环中编写此语句,Thread main 将继续执行。在线程 t 完成后,线程 main 不应该继续执行吗?

t.join(1000);

但是,bucle 继续执行。据我所知,这两行属于线程主线 - 同时(t.isAlive()) - threadMessage("还在等待...")

我试图理解这个链接的一个例子:

Java tutorial

提前感谢您的帮助!!!

【问题讨论】:

  • 输出中有什么不明白的地方?你期望什么输出,为什么?

标签: java multithreading join


【解决方案1】:

查看join() 方法的文档here。就是这么说的:

最多等待几毫秒让该线程终止。

您将 1000 传递给 join(),这意味着主线程将最多等待 1 秒,然后再继续,无论 thread t 是否完成。线程 t 的休眠超时时间为 4 秒,因此,主线程将始终在 t 之前完成(在加入超时之后)。

如果你想让主线程永远等待,你需要使用join()(即不带任何参数)。

【讨论】:

    【解决方案2】:
    while (t.isAlive()) {
        threadMessage("Still waiting...");
        // Wait maximum of 1 second
        // for MessageLoop thread
        // to finish.
        t.join(1000);
    }
    

    t.join(1000) 表示等待线程 t 死亡 1000 毫秒。 t 在打印所有行之前不会死。场景是 t.join(1000) 每秒超时,并且 t 还活着(因为每次打印一行时它会休眠 4 秒)。 join(1000) 超时和t.isAlive() 为真,因此您的主线程将打印出Still waiting.. 一旦线程t 完成其工作,t.isAlive() 将为假,它会中断while 循环然后打印Finally

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-30
      • 1970-01-01
      • 2016-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多