---
title: "并发包compareAndSet的疑惑？为什么没有对应的compare,If Not Equals,Then Set的方法呢？"
author: "atell"
date: "2012-04-01T20:36:27Z"
tags: []
categories: ["编程语言"]
slug: "compareandset-compare-if-not-equals-then-set"
draft: false
lastmod: "2012-04-01T21:24:47Z"
id: 1472878
url: "https://atell.iteye.com/blog/1472878"
---

```
public final boolean compareAndSet(boolean expect,boolean update)
如果当前值 == 预期值，则以原子方式将该值设置为给定的更新值。
```

  并发包的这个方法，看起来意思是compare，If Equals，Then Set

我有个疑惑，为什么没有对应的compare,If Not Equals,Then Set的方法呢 ？

比如，以下场景，就无法使用compareAndSet：

```
if(a != b){
  a = b;
}

if(a != c){
  a = b;
}
```

 

因为我觉得，compare，If Equals，Then Set 和 compare,If Not Equals,Then Set 是不能互相实现对方的，所以应该要有另外的方法才完整。

 

 

查到了：原来是因为compareAndSet是cpu支持的，没有 compare,If Not Equals,Then Set是因为cpu不支持。

http://tomyz0223.iteye.com/blog/770677