title: two java threads, the first to finish should interrupt the other
body: <p>I have a long task that will have a dedicated thread, say: </p>
  
  <pre><code>public static class WorkerThread extends Thread{
  
      @Override public void run () {
          for (int i = 1; i&lt;=10; i++) {
              System.out.println("worker thread progress: " + i + "/10");
              try{Thread.sleep(1000);} catch (InterruptedException ignore) {}
          }
  
      System.out.println("the worker thread HAS FINISHED!");
  
      }
  
  }
  </code></pre>
  
  <p>During this task, i want to listen to the commandline for user cancellation of the long task.
  Due to the peculiarities of System.in, the code is the following (that is if you want an interruptable console reading, you are forced to use polling):</p>
  
  <pre><code>public static class InputThread extends Thread {
  
      @Override public void run() {
         try{
             StringBuilder sb = new StringBuilder(); 
  
             do {
                  while (System.in.available()==0) { Thread.sleep(200); }
  
                  sb.append((char)System.in.read());
  
             } while (!sb.toString().equals("cancel\n"));
  
             System.out.println("the user-input thread HAS FINISHED!");
  
         } catch (IOException ignored) {} catch (InterruptedException ie) {}
      }
  
  }
  </code></pre>
  
  <p>Ok, now let's use the two threads. The cases are:</p>
  
  <ul>
  <li>WorkerThread finishes before of InputThread. In this case i have to (gracefully) interrupt the InputThread, because there is no more the possibility for the user to cancel the thread</li>
  <li>InputThread finishes before of WorkerThread. The user has entered "cancel" command and so i have to (gracefully) interrupt the WorkerThread</li>
  </ul>
  
  <p>By gracefully i mean that the code must be interruptable of course, but this is not the point of the question. 
  The question is: after i have started the two threads, how do i wait for "the first one to finish"? </p>
  
  <pre><code>public static void main (String [] args) throws InterruptedException {
  
      InputThread it = new InputThread();
  
      it.start();
  
      WorkerThread wt = new WorkerThread();
  
      wt.start();
  
  
  }
  </code></pre>