JUC并发编程十 并发架构--Unsafe
生活随笔
收集整理的這篇文章主要介紹了
JUC并发编程十 并发架构--Unsafe
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Unsafe提供了非常底層的,操作內存,線程的方法.Unsafe對象不能直接調用,只能通過反射獲得.
import lombok.Data; import sun.misc.Unsafe;import java.lang.reflect.Field;public class TestUnsafe {public static void main(String[] args) throws Exception {Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");theUnsafe.setAccessible(true);Unsafe unsafe = (Unsafe)theUnsafe.get(null);System.out.println(unsafe);// 1. 獲取域的偏移地址long idOffset = unsafe.objectFieldOffset(Student.class.getDeclaredField("id"));long nameOffset = unsafe.objectFieldOffset(Student.class.getDeclaredField("name"));Student student = new Student();System.out.println(student);// 2. 執行cas操作unsafe.compareAndSwapInt(student,idOffset,0,1);unsafe.compareAndSwapObject(student,nameOffset,null,"小明");// 3. 驗證System.out.println(student);} }@Data class Student{volatile int id;volatile String name; }使用Unsafe構建自己的原子類
import sun.misc.Unsafe;import java.util.ArrayList; import java.util.List;public class TestMyAtomicInteger {public static void main(String[] args) {Account.demo(new MyAtomicInteger(10000));} }class MyAtomicInteger implements Account{private volatile int value; // 使用cas,必須是volatileprivate static final long valueOffset; // 獲取域的偏移量private static final Unsafe UNSAFE;static{UNSAFE = UnsafeAccessor.getUnsafe();try {valueOffset = UNSAFE.objectFieldOffset(MyAtomicInteger.class.getDeclaredField("value"));} catch (NoSuchFieldException e) {e.printStackTrace();throw new RuntimeException(e);}}public int getValue(){return value;}public void decrement(int amount){while(true){int prev = this.value;int next = prev - amount;if(UNSAFE.compareAndSwapInt(this,valueOffset,prev,next)){break;}}}public MyAtomicInteger(int value){this.value = value;}@Overridepublic int getBalance() {return value;}@Overridepublic void withdraw(int amount) {decrement(amount);} }interface Account{// 設置余額int getBalance();void withdraw(int amount);static void demo(Account account){List<Thread> ts = new ArrayList<>();for (int i = 0; i < 1000; i++) {// 創建1000個線程,每個線程減去10ts.add(new Thread(()->{account.withdraw(10);}));}ts.forEach(Thread::start);ts.forEach(t->{try {t.join();} catch (InterruptedException e) {e.printStackTrace();}});System.out.println(account.getBalance());} } import sun.misc.Unsafe;import java.lang.reflect.Field;public class UnsafeAccessor {private static final Unsafe unsafe;static{try {Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");theUnsafe.setAccessible(true);unsafe = (Unsafe)theUnsafe.get(null);} catch (Exception e) {throw new Error(e);}}public static Unsafe getUnsafe(){return unsafe;} }總結
以上是生活随笔為你收集整理的JUC并发编程十 并发架构--Unsafe的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JUC并发编程九 并发架构--CAS
- 下一篇: 网络编程BIO,NIO一