我正在阅读一些android服务代码,它处理gps坐标并设置AtomicReference与new Object为1时间:
public class SingleLocationUpdateService extends ServicePart {
private final AtomicReference<GPSUpdater> currentUpdater = new AtomicReference<>();
@Override
protected boolean onStart() {
lastSaverModeOn = mService.getSettings().getRootSettings().isSaverModeOn();
if (mService.getSettings().getRootSettings().isStopMileageInWorkOn()) {
if (lastSaverModeOn) {
return false;
}
}
singleUpdateSeconds = mService.getSettings().getRootSettings().getGpsRareUpdateSeconds();
***currentUpdater.set(new GPSUpdater());***
mService.getExecutor().schedule(currentUpdater.get(), 10, TimeUnit.SECONDS);
return true;
}
然后调度程序执行这个:
private class GPSUpdater implements Runnable, LocationListener {
@Override
public void run() {
if (!isCurrentRunning()) {
return;
}
Log.d(TAG, "Requesting single location update");
final LocationManager lm = (LocationManager) mService.getSystemService(Context.LOCATION_SERVICE);
try {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this, Looper.getMainLooper());
} catch (Throwable t) {
Log.e(TAG, "Failed to request single location update", t);
}
reschedule();
}
private boolean isCurrentRunning() {
return isStarted() && currentUpdater.get() == GPSUpdater.this;
}
private void reschedule() {
final LocationManager lm = (LocationManager) mService.getSystemService(Context.LOCATION_SERVICE);
lm.removeUpdates(this);
final GPSUpdater next = new GPSUpdater();
if (isStarted() && currentUpdater.compareAndSet(GPSUpdater.this, next)) {
Log.d(TAG, "Rescheduling single location updater");
mService.getExecutor().schedule(next, 10, TimeUnit.SECONDS);
}
}
在调试器中,如果我运行currentUpdater.compareAndSet(GPSUpdater.this, next) 1次它返回true,因此意味着新的GPSUpdater(在onStart()中设置)== GPSUpdater.this。然后将AtomicReference设置为next。接下来是新的GPSUpdater。但是如果你计算currentUpdater.compareAndSet(GPSUpdater.this, next) 2次,它将返回false。所以for 2 time new gpsupdatater != GPSUpdater.this。怎样才能正确地解释呢?如果我创建两个新的对象引用-只有第一个将等于它的类引用?为什么?
通过分别调用new GPSUpdater()
来创建类GPSUpdater的两个不同对象。因此,如果你想比较两个对象,最好使用equals()方法。如果您自己编写了GPSUpdate类,则可能需要重写equals()
方法以产生适当的结果。我的意思是,如果你定义了两个相等的对象,equals应该返回true。如果您使用==
操作符检查两个对象是否相同,则只检查引用而不是对象的真正"内容"