how to restart a Thread?
-
15-10-2019 - |
Question
It is a RMI Server object , so many sethumanActivity() might be run , how do i make sure the previous changeToFalse thread will be stop or halt before the new changeToFalse run? t. interrupt
?
Basically when sethumanActivity() is invoke , the humanActivity will be set to true , but a thread will be run to set it back to false. But I am thinking for how to disable or kill the thread when another sethumanActivity() invoked?
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;
}
}
Edited after the help of 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;
}
}
Solution
Use an ExecutorService. The ExecutorService will create a single thread and you can submit runnables to them as many times as you want.
ExecutorService service = Executors.newSingleThreadExecutor();
Then in your code
@Override
public void sethumanActivity() throws RemoteException {
// TODO Auto-generated method stub
humanActivity = true;
service.submit(cf);
}
Also for the sake of correctness, you are unsafely writing to the humanActivity field. There is the possibility of stale reads. There are many articles that talk about visibility one you can check out here.
OTHER TIPS
Thread.interrupt()
breaks waits, Thread.join()
waits for a thread to finish before proceeding.