Skip to content

Instantly share code, notes, and snippets.

@martijndwars
Last active September 12, 2019 07:50
Show Gist options
  • Save martijndwars/a5a5065c80be34ba299548313f195d97 to your computer and use it in GitHub Desktop.
Save martijndwars/a5a5065c80be34ba299548313f195d97 to your computer and use it in GitHub Desktop.
ThreadDeath example. The main thread starts a new thread, then stops the new thread. The new thread catches the ThreadDeath exception, giving it a chance to clean up, before rethrowing the exception and terminating.
package nl.martijndwars.oshell;
public class Foo {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new Bar());
thread.start();
Thread.sleep(3000);
thread.stop();
}
static class Bar implements Runnable {
@Override
public void run() {
try {
repeat();
} catch (ThreadDeath e) {
System.err.println("Caught ThreadDeath, but I will loop anyway. Muahahah!");
repeat();
}
}
private void repeat() {
while (true) {
System.out.println("Hi");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment