How to stop the same thread from running multiple instances

I have a daemon thread which is started when a page is opened. The thread is then stopped when the page is closed. So in my class which holds the thread, I have it created like this: class A { private static volatile boolean isStopped=false; //this method is called then the page is loaded public void testListener() { Thread listener = new Thread(new Runnable() { public void run() { while(!isStopped) { //perform listener event try { //after every event sleep for a while Thread.sleep(1000 *2) } catch(InterruptedException e){} } } }); } listener.setName("Test-Server-Daemon"); listener.setDaemon(true); listener.start(); // reset back to false so thread can be restarted when the page load event, // call this method instance if (isStopped) { isStopped=false; } } /**This is called when page is closed**/ public static void stopListener() { isStopped=true; } } Upon investigation, I have noticed that when the page is closed and not opened again within say 30 seconds interval, the thread is gracefully stopped. But when the page is closed and re-opened within say 2 seconds interval the old thread does not get stopped and hence runs simultaneously with a new one. And so as you can see from below image, I have the same thread started again when I close and quickly open the page. Do anyone knows how to prevent this from occurring? I have tried using thread `interrupt` where I reset the mutex but no joy. **EDITED:** isStopped is `volatile`. ![enter image description here][1] [1]: http://i.stack.imgur.com/92fQs.png

以上就是How to stop the same thread from running multiple instances的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏