I’m aware of this question here 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:
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.