我有一个守护程序线程,它在打开页面时启动。关闭页面后,线程将停止。因此,在保存线程的类中,我将其创建为:

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;
  }
}


经调查,我注意到当页面关闭且在30秒的间隔内未再次打开时,该线程会正常停止。

但是,当关闭页面并在2秒的间隔内重新打开页面时,旧线程不会停止,因此与新线程同时运行。

从下图可以看出,关闭并快速打开页面后,我再次启动了相同的线程。

有谁知道如何防止这种情况发生?

我尝试使用线程interrupt重设互斥锁,但没有任何乐趣。

编辑:

isStopped是volatile

最佳答案

要遵循@Jordão的回答,isStopped变量应该是每个线程的值。我建议使用类似AtomicBoolean的方法,并将线程代码更改为近似值:

public AtomicBoolean testListener() {
    final AtomicBoolean isStopped = new AtomicBoolean(false);
    Thread listener = new Thread(new Runnable() {
        public void run() {
            while(!isStopped.get()) {
                ...
            }
        }
    });
    listener.setName("Test-Server-Daemon");
    listener.setDaemon(true);
    listener.start();
    return isStopped;
}


然后回到页面控制器中,您可以执行以下操作:

AtomicBoolean isStopped = testListener();
// do the page stuff
...
// when done stop the thread
isStopped.set(true);

08-04 14:59