zoukankan      html  css  js  c++  java
  • Java高性能编程-线程安全-1.2.2原子操作

    CAS机制的使用

    AtomicInteger 就是对 unsafe 类进行封装

    手动实现

    import java.lang.reflect.Field;
    import sun.misc.Unsafe;
    
    public class CounterUnsafe {
    
    	volatile int i = 0;
    
    	private static Unsafe unsafe = null;
    
    	// i字段的偏移量
    	private static long valueOffset;
    
    	static {
    
    		try {
    			Field field = Unsafe.class.getDeclaredField("theUnsafe");
    			field.setAccessible(true);
    			unsafe = (Unsafe) field.get(null);
    
    			Field fieldi = CounterUnsafe.class.getDeclaredField("i");
    			valueOffset = unsafe.objectFieldOffset(fieldi);
    
    		} catch (NoSuchFieldException | IllegalAccessException e) {
    			e.printStackTrace();
    		}
    
    	}
    
    	public void add() {
    
    		for (;;) {
    
    			int current = unsafe.getIntVolatile(this, valueOffset);
    			if (unsafe.compareAndSwapInt(this, valueOffset, current, current + 1))
    				break;
    		}
    	}
    
    }
    

     运行

    public class Demo1_CounterTest {
    
    	public static void main(String[] args) throws InterruptedException {
    		final CounterUnsafe ct = new CounterUnsafe();
    		for (int i = 0; i < 6; i++) {
    			new Thread(new Runnable() {
    
    				@Override
    				public void run() {
    					// TODO Auto-generated method stub
    					for (int j = 0; j < 1000; j++) {
    						ct.add();
    						System.out.println("dome...");
    					}
    				}
    
    			}).start();
    
    			Thread.sleep(6000L);
    			System.out.println(ct.i);
    		}
    
    	}
    
    }
    

      

     

  • 相关阅读:
    XML应用程开发--下
    XML应用程序开发--上
    TCP通信客户端简单示例
    TCP网络通信服务器端简单示例
    XML基本内容学习笔记
    如何在Qt的widget上右键显示菜单
    关于双指针遍历
    常见的四种排序算法
    JAVA Class13
    JAVA练习
  • 原文地址:https://www.cnblogs.com/Jomini/p/13067891.html
Copyright © 2011-2022 走看看