java - Self interruption of a thread -


the task make free thread interrupted when definite period of time expires. code doesn't work @ all. @ break points have irrelevant threads. well, have come end of wit. me?

public class hotthread implements runnable {      public hotthread() {         this.file = null;             } }   public class freethread extends hotthread {      private final int timeout;     timer timer;     interruptbytimer task;       public freethread(int timeout) {         super();         this.timeout = timeout;         timer = new timer();         task = new interruptbytimer(timer);         timer.schedule(task, timeout);     }       private class interruptbytimer extends timertask {         timer timer;         public interruptbytimer(timer timer){             this.timer = timer;         }          @override         public void run(){             interruptthisthread(timer);         }     }      public void interruptthisthread(timer timer){             timer.cancel();             thread.currentthread().interrupt();     }  } 

from java concurrency tutorial :

a thread sends interrupt invoking interrupt on thread object thread interrupted. interrupt mechanism work correctly, the interrupted thread must support own interruption.

this support must implemented in thread run method (which don't see in code). there several example in tutorial. in run method should trick :

while( continuework) {     dosomework();     if (thread.interrupted()) {         // we've been interrupted: no more crunching.         return;     } } 

for interrupting thread in timertask, you'll need have reference it, can pass constructor :

public class freethread extends hotthread {      private final int timeout;     timer timer;     interruptbytimer task;       public freethread(int timeout) {         super();         this.timeout = timeout;         timer = new timer();         task = new interruptbytimer(timer, thread.currentthread());         timer.schedule(task, timeout);     }       private class interruptbytimer extends timertask {         timer timer;         thread thread;         public interruptbytimer(timer timer, thread thread){             this.timer = timer;             this.thread = thread;         }         @override         public void run(){              interruptthisthread(timer);         }     }      public void interruptthisthread(timer timer, thread thread){         timer.cancel();         thread.interrupt();     }  } 

btw, don't understand why pass timer task, cancel() called in interruptthisthread anyway.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -