java - Loop task for given time using Thread.sleep() -


i have method loop given time. have tried creating 2 threads 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 cant seem break loop, t never interrupted reason.

the isinterrupted method more of haspendinginterruption waseverinterrupted. flag automatically cleared when interruptedexception thrown in thread (which can happen @ points, when call sleep), or if calls interrupted() (which different isinterrupted()).

read official java tutorial on interrupts more info.

threads have exited can not have pending interruptions.

however, not way limit main thread's run time. checking time in every iteration achieve want:

long end = system.currenttimemillis() + length; while(system.currenttimemillis() < end){     runcurrentpres(current); } 

note checks between each runcurrentpres call, if function takes long time execute, loop finish little later intended. is, however, same behavior original code would've had if worked.


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -