Say I have something like this
public void run(){
Thread behaviourThread = new Thread(abstractBehaviours[i]);
behaviourThread.start();
}
And I want to wait until the executeBehaviours [i] method completes or starts within 5000 milliseconds. How should I do it? behaviourThread.join (5000) does not seem to do this afaik (something is wrong with my code, and I put it aside).
The entire abstract abstract Behavior class is, of course, Runnable. I don’t want to implement it inside each launch method, since it seems ugly, and there are many different ways of behavior, I would prefer to use it in the call / executing thread and do it only once.
Decision? The first time I did something like carving. Thank!
edit: Thus, interrupting the solution would be ideal (requiring minimal changes to the implementation of AbstractBehaviour). BUT I need the thread to stop if it has finished OR the 5000 milliseconds have passed, so something like the following will not work, because the thread may end before the while loop in the parent thread. Make sense? Any ways to get around this, I'd like to make it from a thread that starts threads, obviously.
long startTime = System.currentTimeMillis();
behaviourThread.start();
while(!System.currentTimeMilis - startTime < 5000);
behaviourThread.interrupt();
try {
behaviourThread.join();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
edit: nevermind I see that there is a Thread.isAlive () method, everything is solved, I think
source
share