简体   繁体   English

Java中volatile变量的使用

[英]Use of volatile variable in Java

I was reading a lot of forums and tutorials about volatile variables, but still not working for me.我阅读了很多关于 volatile 变量的论坛和教程,但仍然不适合我。 I'm working on app for Android in Android studio in Java.我正在 Java 的 Android Studio 中开发适用于 Android 的应用程序。

I have main UI thread and from that I'm creating another using Runnable.我有主 UI 线程,然后我正在使用 Runnable 创建另一个线程。 I need to shere two variables between these two threads.我需要在这两个线程之间传递两个变量。 UI thread changes these variables, another thread reads these variables. UI 线程更改这些变量,另一个线程读取这些变量。

Here is a fragment of my code.这是我的代码片段。 The code is not complete (not all lines about sensors - bcs it works well).代码不完整(并非所有关于传感器的行 - bcs 运行良好)。 I just don't know how to connect x,y in both threads that changes in UI will be visible in another thread.我只是不知道如何在两个线程中连接 x,y,UI 中的更改将在另一个线程中可见。

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.你应该只声明一对。

class Globals {

    public static volatile float x = 0;
    public static volatile float y = 0;

}

You can then 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 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.这不一定是好的做法,我可能会声明一个可变的Point类并将其保存在单例中,但至少您只需要共享一个实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM