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);
		}

	}

}

  

 

原文地址:https://www.cnblogs.com/Jomini/p/13067891.html