title: Java: Stopping a thread that has run for too long?
body: <p>Say I've got something like this</p>
  
  <pre><code>public void run(){
      Thread behaviourThread = new Thread(abstractBehaviours[i]);
      behaviourThread.start();
  }
  </code></pre>
  
  <p>And I want to wait until abstractBehaviours[i] run method has either finished or run for 5000 milliseconds. How do I do that? behaviourThread.join(5000) doesn't seem to do that afaik (something is wrong with my code and I've put it down to that).</p>
  
  <p>All the abstract abstractBehaviour class is of course Runnable. I don't want to implement it inside each run method as that seems ugly and there are many different behaviours, I'd much rather have it in the calling/executing thread and do it just once.</p>
  
  <p>Solutions? First time doing something as threaded as this. Thanks!</p>
  
  <p>edit: So the interrupting solution would be ideal (requiring minimal changes to AbstractBehaviour implementations). BUT I need the thread to stop if it has finished OR 5000 milliseconds have passed so something like the following would not work because the thread may finish before the while loop in the parent thread has. Make sense? Any ways around this, I'd love to do it from within the thread that starts the threads obviously.</p>
  
  <pre><code>long startTime = System.currentTimeMillis();
  behaviourThread.start();
  while(!System.currentTimeMilis - startTime &lt; 5000);
  behaviourThread.interrupt();
  try {
      behaviourThread.join();
  } catch (InterruptedException e1) {
      e1.printStackTrace();
  }
  </code></pre>
  
  <p>edit: nevermind I see there is a Thread.isAlive() method, all solved I think</p>