Most efficient method for a thread to wait for a specific time in Java
I'm aware of this question her开发者_Go百科e but I have a slightly different question. If I wish to hand-code via the various Thread methods myself (not via utility classes or Quartz) the running of a Thread at a particular time, then what would be the most efficient (in terms of overhead) to code this.
I considered:
boolean wasInterrupted = false;
while (System.currentTimeMillis() < executionTimeInMillis) {
try {
Thread.sleep(X);
} catch (InterruptedException ie) {
wasInterrupted = true;
}
}
if (!wasInterrupted) {
doMyThing();
}
Is there a better way? Is this primitive and naive?
You have 3 basic possibilities:
- Thread.sleep(...): causes the currently executing thread to sleep (cease execution) for the specified number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors;
- Thread.yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute;
- Monitors: you call wait on the object you want to lock and you release the lock by calling notify on the same object. For more information look at the javadoc: http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/lang/Object.html#wait()
The best way is to use monitors because you know when you acquire lock and when you release it. Moreover, it allows to let other threads to execute. If you want to understand why sleep and yield methods must be avoid, read http://www.javamex.com/tutorials/threads/yield.shtml.
I would use a Timer/TimerTask combination, starting the thread you want to run in the run() method of the TimerTask (Alternatively, you could just do the work directly in the TimerTask's run() method, which will then be performed in the Timer's thread). That approach doesn't need try/catch blocks or a while loop, and strikes me as a bit more direct.
Check out:
http://download.oracle.com/docs/cd/E17476_01/javase/1.4.2/docs/api/java/util/Timer.html
http://download.oracle.com/docs/cd/E17476_01/javase/1.4.2/docs/api/java/util/TimerTask.html
精彩评论