有一种简单的方法可以保护变量只能由一个线程同时加入?

Nul*_*ion -1 java multithreading android

我的" SharedPreferences" 有一个变量,有两个不同的线程,一个在服务中,一个在一个活动中.

有一种简单的方法可以保护这个变量一次被两个线程加入吗?

我需要保护这段代码:

            configEditor.putString("mylatitude", ""+currentLocation.getLatitude());
            configEditor.putString("mylongitude", ""+currentLocation.getLongitude());
            configEditor.commit();
Run Code Online (Sandbox Code Playgroud)

我试过这个,但不起作用:

Object LOCK = new Object();
                synchronized (LOCK){
                configEditor.putString("mylatitude", ""+currentLocation.getLatitude());
                configEditor.putString("mylongitude", ""+currentLocation.getLongitude());
                configEditor.commit();
                }
Run Code Online (Sandbox Code Playgroud)

谢谢

app*_*pps 6

Object LOCK = new Object();


 synchronized (LOCK) {
     // lines of Java code that has to be thread safe
    }
Run Code Online (Sandbox Code Playgroud)

编辑:当代码修改几个变量并且必须是线程安全的时,编辑代码以完全适应情况.对于单个变量(如问题标题中所示)锁定变量本身,您不需要单独的锁定.