Java并发编程之原子变量
程序员文章站
2022-06-23 23:43:38
原子变量比锁的粒度更细,量级更轻,并且对于在多处理器系统上实现高性能的并发代码来说是非常关键的。 原子变量类相当于一种泛化的 volatile 变量,能够支持原子的和有条件的读-改-写操作。 原子类在内部使用现代 CPU 支持的 CAS 指令来实现同步。这些指令通常比锁更快。 原子更新基本类型 At ......
原子变量比锁的粒度更细,量级更轻,并且对于在多处理器系统上实现高性能的并发代码来说是非常关键的。
原子变量类相当于一种泛化的 volatile 变量,能够支持原子的和有条件的读-改-写操作。
原子类在内部使用现代 cpu 支持的 cas 指令来实现同步。这些指令通常比锁更快。
原子更新基本类型
- atomicboolean - 原子更新布尔类型。
- atomicinteger - 原子更新整型。
- atomiclong - 原子更新长整型。
示例:
public class atomicintegerdemo { public static void main(string[] args) throws interruptedexception { executorservice executorservice = executors.newfixedthreadpool(5); atomicinteger count = new atomicinteger(0); for (int i = 0; i < 1000; i++) { executorservice.submit((runnable) () -> { system.out.println(thread.currentthread().getname() + " count=" + count.get()); count.incrementandget(); }); } executorservice.shutdown(); executorservice.awaittermination(30, timeunit.seconds); system.out.println("final count is : " + count.get()); } }
原子更新数组
- atomicintegerarray - 原子更新整型数组里的元素。
- atomiclongarray - 原子更新长整型数组里的元素。
- atomicreferencearray - 原子更新引用类型数组的元素。
- atomicbooleanarray - 原子更新布尔类型数组的元素。
示例:
public class atomicintegerarraydemo { private static atomicintegerarray atomicintegerarray = new atomicintegerarray(10); public static void main(final string[] arguments) throws interruptedexception { for (int i = 0; i < atomicintegerarray.length(); i++) { atomicintegerarray.set(i, i); } thread t1 = new thread(new increment()); thread t2 = new thread(new compare()); t1.start(); t2.start(); t1.join(); t2.join(); system.out.println("final values: "); for (int i = 0; i < atomicintegerarray.length(); i++) { system.out.print(atomicintegerarray.get(i) + " "); } } static class increment implements runnable { public void run() { for (int i = 0; i < atomicintegerarray.length(); i++) { int add = atomicintegerarray.incrementandget(i); system.out.println(thread.currentthread().getname() + ", index " + i + ", value: " + add); } } } static class compare implements runnable { public void run() { for (int i = 0; i < atomicintegerarray.length(); i++) { boolean swapped = atomicintegerarray.compareandset(i, 2, 3); if (swapped) { system.out.println(thread.currentthread().getname() + ", index " + i + ", value: 3"); } } } } }
原子更新引用类型
- atomicreference - 原子更新引用类型。
- atomicreferencefieldupdater - 原子更新引用类型里的字段。
- atomicmarkablereference - 原子更新带有标记位的引用类型。可以原子更新一个布尔类型的标记位和应用类型。
public class atomicreferencedemo { private static string message; private static person person; private static atomicreference<string> armessage; private static atomicreference<person> arperson; public static void main(string[] args) throws interruptedexception { thread t1 = new thread(new myrun1()); thread t2 = new thread(new myrun2()); message = "hello"; person = new person("phillip", 23); armessage = new atomicreference<string>(message); arperson = new atomicreference<person>(person); system.out.println("message is: " + message + "\nperson is " + person.tostring()); system.out.println("atomic reference of message is: " + armessage.get() + "\natomic reference of person is " + arperson.get().tostring()); t1.start(); t2.start(); t1.join(); t2.join(); system.out.println("\nnow message is: " + message + "\nperson is " + person.tostring()); system.out.println("atomic reference of message is: " + armessage.get() + "\natomic reference of person is " + arperson.get().tostring()); } static class myrun1 implements runnable { public void run() { armessage.compareandset(message, "thread 1"); message = message.concat("-thread 1!"); person.setage(person.getage() + 1); person.setname("thread 1"); arperson.getandset(new person("thread 1", 1)); system.out.println("\n" + thread.currentthread().getname() + " values " + message + " - " + person.tostring()); system.out.println("\n" + thread.currentthread().getname() + " atomic references " + message + " - " + person.tostring()); } } static class myrun2 implements runnable { public void run() { message = message.concat("-thread 2"); person.setage(person.getage() + 2); person.setname("thread 2"); armessage.lazyset("thread 2"); arperson.set(new person("thread 2", 2)); system.out.println("\n" + thread.currentthread().getname() + " values: " + message + " - " + person.tostring()); system.out.println("\n" + thread.currentthread().getname() + " atomic references: " + armessage.get() + " - " + arperson.get().tostring()); } } static class person { private string name; private int age; person(string name, int age) { this.name = name; this.age = age; } public string getname() { return name; } public void setname(string name) { this.name = name; } int getage() { return age; } void setage(int age) { this.age = age; } @override public string tostring() { return "[name " + this.name + ", age " + this.age + "]"; } } }
原子更新字段类
- atomicintegerfieldupdater - 原子更新整型的字段的更新器。
- atomiclongfieldupdater - 原子更新长整型字段的更新器。
- atomicstampedreference - 原子更新带有版本号的引用类型。该类将整型数值与引用关联起来,可用于原子的更新数据和数据的版本号,可以解决使用 cas 进行原子更新时可能出现的 aba 问题。
public class atomicstampedreferencedemo { private final static string init_ref = "abc"; public static void main(string[] args) throws interruptedexception { atomicstampedreference<string> asr = new atomicstampedreference<>(init_ref, 0); system.out.println("初始对象为:" + asr.getreference()); final int stamp = asr.getstamp(); executorservice executorservice = executors.newfixedthreadpool(100); for (int i = 0; i < 100; i++) { executorservice.submit(() -> { try { thread.sleep(math.abs((int) (math.random() * 100))); } catch (interruptedexception e) { e.printstacktrace(); } if (asr.compareandset(init_ref, thread.currentthread().getname(), stamp, stamp + 1)) { system.out.println(thread.currentthread().getname() + " 修改了对象!"); system.out.println("新的对象为:" + asr.getreference()); } }); } executorservice.shutdown(); executorservice.awaittermination(60, timeunit.seconds); } }
免费java资料需要自己领取,涵盖了java、redis、mongodb、mysql、zookeeper、spring cloud、dubbo高并发分布式等教程,一共30g。
传送门:https://mp.weixin.qq.com/s/jzddfh-7ynudmkjt0irl8q