出現問題。我有一個派生的線程,必須調用它的finally塊。假設下面的代碼,是否有可能確保最終在runnable中被調用?確保runnig終於在產生的線程,當spawner命中RuntimeException?
import org.junit.Test;
public class ThreadTest {
@Test
public void testThreadFinally() throws InterruptedException {
Runnable r = new Runnable() {
@Override
public void run() {
try {
System.out.println("Going to sleep...");
Thread.sleep(1000);
System.out.println("slept 1000 ms");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("Must print this.");
}
}
};
Thread t = new Thread(r);
t.setDaemon(false);
t.start();
Thread.sleep(500);
System.out.println("main thread about to throw runtime...");
throw new RuntimeException("fail");
}
}
是的,多數民衆贊成,認爲我再造了另一個問題,但這是一個死衚衕......謝謝 – Tomas 2009-11-18 20:18:33