【发布时间】: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