Я читал этот учебник Sun по теме .
Я нашел там блок кода, который, я думаю, может быть заменен кодом из меньшего количества строк. Интересно, почему опытные программисты 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!");