Reputation: 568
I currently have a method i would like to loop for a given time. I have tried creating two threads like this
Thread t = new Thread();
t.start();
Runnable r = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(length);
t.interrupt();
} catch (InterruptedException ex) {
}
}
};
Thread s = new Thread(r);
s.start();
while(!t.isInterrupted()){
runCurrentPres(current);
}
But I cant seem to break the loop, t is never interrupted for some reason.
Upvotes: 1
Views: 677
Reputation: 568
Using your suggestions i went with
long end = System.currentTimeMillis() + length;
while(System.currentTimeMillis() < end){
runCurrentPres(current);
}
as mentioned in comments, the runcurrent takes time to execute because of a for loop. therefor i changed the solution to check before each iteration of the for loop, it ended up like this, and works just as intended
long time = System.currentTimeMillis();
while (time + length > System.currentTimeMillis()) {
files = updateFiles(current);
for (File f : files) {
if(time + length < System.currentTimeMillis()){
break;
}
And yes, the solution with the while(true) inside the thread used 70% cpu
Upvotes: 0
Reputation: 6876
The isInterrupted
method is really more of a hasPendingInterruption
than wasEverInterrupted
. The flag is automatically cleared when an InterruptedException
is thrown in that thread (which can only happen at certain points, like when you call sleep), or if anyone calls interrupted()
(which is different from isInterrupted()
).
Read the official Java tutorial on Interrupts for more info.
Threads that have exited can not have pending interruptions.
However, this is not a good way to limit your main thread's run time. Checking the time in every iteration would achieve what you want:
long end = System.currentTimeMillis() + length;
while(System.currentTimeMillis() < end){
runCurrentPres(current);
}
Note that this only checks between each runCurrentPres
call, so if that function takes a long time to execute, your loop will finish a little later than intended. This is, however, the same behavior that your original code would've had if it worked.
Upvotes: 3
Reputation: 24464
So what about this?
long time = System.currentTimeMillis();
while (time + length > System.currentTimeMillis()) {
runCurrentPres(current);
}
No need to use threads.
Upvotes: 2