android - Use of volatile variable in Java -


i reading lot of forums , tutorials volatile variables, still not working me. i'm working on app android in android studio in java.

i have main ui thread , i'm creating using runnable. need shere 2 variables between these 2 threads. ui thread changes these variables, thread reads these variables.

here fragment of code. code not complete (not lines sensors - bcs works well). don't know how connect x,y in both threads changes in ui visible in thread.

thanks 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 1 pair.

class globals {      public static volatile float x = 0;     public static volatile float y = 0;  } 

you can change them anywhere:

    public void onsensorchanged(sensorevent event) {         globals.x = -(float) (event.values[2] / (1000 * 90.0));         globals.y = (float) (event.values[1] / (1000 * 180.0));     } 

this not practice, declare mutable point class , hold in singleton @ least need share 1 instance.


Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -