Consider the following code:
public class ThreadT implements Runnable {
public void run() {
System.out.println("run.");
throw new RuntimeException("Problem");
}
public static void main(String[] args) {
Thread t = new Thread(new ThreadT());
t.start();
System.out.println("End of method.");
}
}
The output I get is:
End of method.
run.
Exception in thread "Thread-0" java.lang.RuntimeException: Problem
Why the output is not like this:
run.
Exception in thread "Thread-0" java.lang.RuntimeException: Problem
End of method.
I believe it's because when you run a new thread beside Main, both threads run at the same time and first it prints out the "End of method", right after it runs the second outprint (which is probably few miliseconds behind.
try this:
public class thread implements Runnable {
public void run() {
System.out.println("run.");
throw new RuntimeException("Problem");
}
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new thread());
t.start();
Thread.sleep(3000);
System.out.println("End of method.");
}
}
What I did here is to put Main thread into sleep for 3 seconds and give time to Thread t to run first.
Or you can also write join() to wait the Thread to finish first. Like this:
public class thread implements Runnable {
public void run() {
System.out.println("run.");
throw new RuntimeException("Problem");
}
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new thread());
t.start();
t.join();
System.out.println("End of method.");
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加