I have the following class:
public class MovementThread extends Thread {
private float[] myObject;
@Override
public void run() {
}
public void setMyObject(float[] array) {
myObject = array;
}
}
The thing is that MovementThread should be running all the time, so I thought about putting a while(true) in the Run method. However, myObject will be updated from another Thread, so it won’t happen if the Thread is stuck in the Run method. Also the code in the run method should not be executed when myObject is being executed.
Is their any non complicated way of doing this ?
I’m just wondering about best practice in this case, which must happen pretty often I reckon.
First things first, standard practice nowadays is to implement runnable rather than extending thread(see "implements Runnable" vs. "extends Thread").
A
while(true)is the correct idea for what to put in the run method. Eventually you would switch over to awhile(someBooleanVariable)so as to provide a way of killing your MovementThread.The current way to make sure that the thread from MovementThread’s run does not conflict with other member calls from other threads is to use synchronized. For simple uses, you can usually prefix the function declaration with synchronized and all such functions will not interweave.
Your sample with all of these modifications:
Note that all reads and writes of myObject are in functions marked synchronized.