I was reading a lot of forums and tutorials about volatile variables, but still not working for me. I'm working on app for Android in Android studio in Java.
I have main UI thread and from that I'm creating another using Runnable. I need to shere two variables between these two threads. UI thread changes these variables, another thread reads these variables.
Here is a fragment of my code. The code is not complete (not all lines about sensors - bcs it works well). I just don't know how to connect x,y in both threads that changes in UI will be visible in another thread.
thanks for any advice.
class MyThread implements Runnable {
public static volatile float x = 0;
public static volatile float y = 0;
GLSurfaceView mGLView;
public MyThread(float xPos, float yPos, GLSurfaceView GLView) {
x=xPos;
y=yPos;
mGLView = GLView;
}
public void run() {
while(true){
((MyGLSurfaceView)mGLView).mRenderer.ball.translateM(x, y, 0);
}
}
}
public class MainActivity extends Activity implements SensorEventListener {
private GLSurfaceView mGLView;
public static volatile float x = 0;
public static volatile float y = 0;
public void onCreate(Bundle savedInstanceState) {
r = new MyThread(x, y, mGLView);
new Thread(r).start();
}
public void onSensorChanged(SensorEvent event) {
r.x = -(float)(event.values[2]/(1000*90.0));
r.y = (float)(event.values[1]/(1000*180.0));
}
}
You should declare just one pair.
You can then change them anywhere:
This is not necessarily good practice, I would probably declare a mutable
Point
class and hold it in a singleton but at least you need to share just one instance.