Is a volatile required in the kill variable that controls the execution of the thread?
public class MyThread extends Thread{
private boolean kill = false;
public void killThread(){
kill = true;
}
@Override
public void run(){
while(!kill){
//do stuff
}
}
}
For example if in some other part of the code (another thread) I do theThreadRef.killThread(); should I expect the thread to stop or is the result unpredictable due to not having declared kill as volatile? I am not sure on this since I update the kill via the killThread method.
Thanks
Yes,
killis a variable shared between threads and must bevolatile. However, consider using Java’s native interruption mechanism, involvingThread.interrupt()andThread.interrupted(), to achieve what you need. Then you won’t need to keep your own variable.