它是一个 RMI 服务器对象,可能会运行很多 sethumanActivity(),我如何确保在新的 changeToFalse 运行之前之前的 changeToFalse 线程将停止或停止?t. interrupt
?
基本上当 sethumanActivity() 被调用时,humanActivity 将被设置为 true ,但将运行一个线程将其设置回 false 。但是我正在考虑如何在另一个 sethumanActivity() 调用时禁用或终止线程?
public class VitaminDEngine implements VitaminD {
public boolean humanActivity = false;
changeToFalse cf = new changeToFalse();
Thread t = new Thread(cf);
private class changeToFalse implements Runnable{
@Override
public void run() {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
humanActivity = false;
}
}
@Override
public void sethumanActivity() throws RemoteException {
// TODO Auto-generated method stub
humanActivity = true;
t.start();
}
public boolean gethumanActivity() throws RemoteException {
// TODO Auto-generated method stub
return humanActivity;
}
}
在SOer的帮助下编辑
package smartOfficeJava;
import java.rmi.RemoteException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class VitaminDEngine implements VitaminD {
public volatile boolean humanActivity = false;
changeToFalse cf = new changeToFalse();
ExecutorService service = Executors.newSingleThreadExecutor();
private class changeToFalse implements Runnable{
@Override
public void run() {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
humanActivity = false;
}
}
@Override
public synchronized void sethumanActivity() throws RemoteException {
humanActivity = true;
service.submit(cf);
}
public synchronized boolean gethumanActivity() throws RemoteException {
return humanActivity;
}
}