【问题标题】:Java - Thread - Problem in one of the Sun's tutorialJava - 线程 - Sun 的教程之一中的问题
【发布时间】:2010-05-03 08:53:36
【问题描述】:

我正在阅读这个Sun's tutorial on Thread

我在那里找到了一段代码,我认为可以用更少行的代码来替换它。我想知道为什么 Sun 的专业程序员可以用更少的代码来完成任务。

我问这个问题是为了知道如果我遗漏了教程想要传达的东西。

代码块如下:

    t.start();

    threadMessage("Waiting for MessageLoop thread to finish");
    //loop until MessageLoop thread exits
    while (t.isAlive()) {
        threadMessage("Still waiting...");
        //Wait maximum of 1 second for MessageLoop thread to
        //finish.
        t.join(1000);
        if (((System.currentTimeMillis() - startTime) > patience) &&
                t.isAlive()) {
            threadMessage("Tired of waiting!");
            t.interrupt();
            //Shouldn't be long now -- wait indefinitely
            t.join();
        }

    }
    threadMessage("Finally!");

我觉得上面的代码可以换成下面这样:

t.start();
t.join(patience); // InterruptedException is thrown by the main method so no need to handle it

if(t.isAlive()) {
    // t's thread couldn't finish in the patience time
    threadMessage("Tired of waiting!");
    t.interrupt();
    t.join();
}

threadMessage("Finally!");

【问题讨论】:

  • 你觉得呢?运行它怎么样?
  • 嗯,在并发代码中,您永远无法知道是否存在可能失败的特殊情况。所以在我看来,“思考”是正确的词.. :)
  • @Robin 我同意,但在这个例子中,我们谈论的是 2 个线程并没有做太多。上面看到的代码基本就是这样了。

标签: java join multithreading


【解决方案1】:
t.join(1000) 

该代码实际上并不应该尽可能聪明,但我猜它是为了演示用法

【讨论】:

  • 同意。特别是,如果运行 sun 代码,将通过 threadMessages 清楚地显示两个线程同时运行。这在 OP 代码中并不明显。
【解决方案2】:

该示例旨在传达同时运行的两个线程,主线程和您启动的线程。该代码实际上并没有做任何有用的事情,但 Suns 示例将显示“仍在等待...”,其中穿插着来自正在打印字符串的线程的消息。

如果您以鳕鱼实际行为的形式来看待它,是的,它们都做同样的事情。 两个例子 1) 启动线程 t 2) 将等待patience ms 3) 中断线程t 4)等它死 5) 从主线程打印“Finally”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    相关资源
    最近更新 更多