繁体   English   中英

AtomicReference中的第二个新对象!= class.this

[英]Second new object != class.this in AtomicReference

我正在读取一些处理gps坐标并使用新对象设置AtomicReference的android服务代码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;
}

然后,sheduler执行以下操作:

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。 因此,有2次新的GPSUpdater!= GPSUpdater.this。 如何正确解释? 如果我创建2个新的对象引用-只有第一个等于其类引用? 为什么? 提前谢谢。

您正在通过为类中的每个对象调用new GPSUpdater()创建两个不同的对象。 因此,如果要比较两个对象,则最好使用equals()方法。 而且,如果您自己编写了GPSUpdate类,则可能需要覆盖equals()方法以产生适当的结果。 我的意思是,如果将两个对象定义为相等,则equals应该返回true。 如果使用==运算符检查两个对象是否相同,则仅检查那里的引用而不是对象的真实“内容”

暂无
暂无

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

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