1.更新器更新的必须是int类型变量,不能是其包装类型。
2.更新器更新的必须是volatile类型的,确保线程之间共享变量时的立即可见性。
3.变量不能是static的,必须是实例变量。因为Unsafe.objectFieldOffset()方法不支持静态变量(CAS操作本质上是通过对象实例的偏移量来直接进行赋值)。
4.更新器只能修改它可见范围的变量,因为更新器是通过反射来得到这个变量,如果变量不可见就会报错。
如果要更新的是包装类型,那么可以使用AtomicReferenceFieldUpdater来进行更新。
package xmg.quest.netty.atomic;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
/**
* @author 作者 : xuminggang
* @version 创建时间:2020年6月3日 上午11:33:48
*
*/
public class AtomicUpdaterTest {
public static void main(String[] args) {
// People person = new People();
// for(int i=0;i<10;i++) {
// Thread thread = new Thread(()-> {
//
// try {
// Thread.sleep(20);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// System.out.println(person.age++);
// });
// thread.start();
// }
People people = new People();
AtomicIntegerFieldUpdater<People> atomic = AtomicIntegerFieldUpdater.newUpdater(People.class, "age");
for(int i=0;i<10;i++) {
Thread thread = new Thread(()-> {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(atomic.getAndIncrement(people));
});
thread.start();
}
}
}
class People{
volatile int age = 1;
}