I am trying to find an elegant way for a child thread (spawned from a main thread) to stop what its doing and tell the main thread something went wrong. I thought that if I invoke mainThread.interrupt() from the child thread by giving the child thread a reference to the main thread, that would do the trick. But it doesn't work all the time. I want to know why. Here's my code below:

The main class:

/**
* IF YOU RUN THIS OFTEN ENOUGH, YOU'LL NOTICE THE "Child Please!" MESSAGE NOT SHOW AT SOME POINT. WHY?
*/
public class InterruptingParentFromChildThread
{
public static void main( String args[] )
{
Thread child = new Thread( new ChildThread( Thread.currentThread() ) );

1000350 wrote:
because the child thread is finished, you need add sleep at the end like follows:

EDITED:

oh, now i see where you are going with this. the child thread ends so the "join()" call completes successfully before the interrupt is registered. interesting race condition, would never have expected that!

EJP wrote:
I'm not convinced about that. The wording in join() suggests that, but the wording in interrupt() definitely does not.

Thread.join() doesn't really provide much in the way of details, but Object.wait() does:

"throws InterruptedException - if any thread interrupted the current thread +before+ or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown."

every jdk method i've used which throws InterruptedException will always throw if entered while a thread is currently interrupted. admitted, i rarely use Thread.join(), so it's possible that method could be different. however, that makes the thread interruption far less useful if it's required to hit the thread while it's already paused.