【问题标题】:Use of volatile variable in JavaJava 中 volatile 变量的使用
【发布时间】:2015-06-10 16:08:09
【问题描述】:

我阅读了很多关于 volatile 变量的论坛和教程,但仍然不适合我。我正在使用 Java 的 Android Studio 开发适用于 Android 的应用程序。

我有主 UI 线程,我正在使用 Runnable 创建另一个主线程。 我需要在这两个线程之间设置两个变量。 UI 线程更改这些变量,另一个线程读取这些变量。

这是我的代码片段。代码不完整(并非所有关于传感器的行 - bcs 它运行良好)。我只是不知道如何在两个线程中连接 x,y,UI 中的更改将在另一个线程中可见。

感谢您的建议。

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));
    }
}

【问题讨论】:

    标签: java android multithreading volatile


    【解决方案1】:

    你应该只声明一对。

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

    然后您可以在任何地方更改它们:

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

    这不一定是好的做法,我可能会声明一个可变的Point 类并将其保存在一个单例中,但至少您只需要共享一个实例。

    【讨论】:

    • 复合操作
    猜你喜欢
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 2013-04-23
    • 1970-01-01
    • 2017-08-09
    • 2015-03-24
    • 1970-01-01
    相关资源
    最近更新 更多