Java 自己动手写一个线程锁

public class CasTip {

	private static Unsafe unsafe = UnsafeObject.getUnsafe();
	int lock = 0;
	static long offset;
	static {
		try {
			offset = unsafe.objectFieldOffset(CasTip.class.getDeclaredField("lock"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		// 0: sun.reflect.Reflection
		// 1: thread.CasTip
		System.out.println(sun.reflect.Reflection.getCallerClass(1).getName());

		final CasTip target = new CasTip();
		new Thread(new Runnable() {
			@Override
			public void run() {
				lock(target);
				System.out.println("lock1");
				unlock(target);
			}
		}).start();

		new Thread(new Runnable() {
			@Override
			public void run() {
				lock(target);
				System.out.println("lock2");
				unlock(target);
			}
		}).start();

	}

	public static void lock(Object o) {
		for (;;) {
			if (unsafe.compareAndSwapInt(o, offset, 0, 1))
				break;
		}
	}

	public static void unlock(Object o) {
		unsafe.compareAndSwapInt(o, offset, 1, 0);
	}

}

猜你喜欢

转载自blog.csdn.net/qq948993066/article/details/80050903