Java中使用Atomic*实现原子锁线程安全

原子锁类型是JDK Atomic* 相关的类。如AtomicInteger、AtomicLong 等等。

package com.forestar.xht.util;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 原子锁
 * 
 * @author PJL
 *
 */
public class AtomicLock {

	private static AtomicInteger flag = new AtomicInteger(0);
	
	/**
	 * 获取锁的值
	 * @return
	 */
	public static int getLockValue() {
		return flag.intValue();
	}

	/**
	 * 阻塞
	 */
	public static void blockingUntilUnlock() {
		while (flag.intValue() == 1) {
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 加锁
	 * 
	 * @return
	 */
	public static int lock() {
		blockingUntilUnlock();

		if (flag.intValue() == 0) {
			return flag.incrementAndGet();
		}
		return flag.intValue();
	}

	/**
	 * 去锁
	 * 
	 * @return
	 */
	public static int unlock() {
		if (flag.intValue() == 1) {
			return flag.decrementAndGet();
		}
		return flag.intValue();
	}

	public static void main(String[] args) {
		for (int i = 1; i <= 10; i++) {
			String name = "thread-" + i;
			new Thread(() -> {
				AtomicLock.lock();
				System.out.println(name + "加锁"+" "+" 值 "+AtomicLock.getLockValue());
				AtomicLock.unlock();
				System.out.println(name + "去锁"+" "+" 值 "+AtomicLock.getLockValue());
			}).start();
		}
	}

}

测试结果:

thread-1加锁  值 1
thread-1去锁  值 0
thread-4加锁  值 1
thread-4去锁  值 0
thread-7加锁  值 1
thread-7去锁  值 0
thread-8加锁  值 1
thread-8去锁  值 0
thread-9加锁  值 1
thread-9去锁  值 0
thread-10加锁  值 1
thread-10去锁  值 0
thread-2加锁  值 1
thread-2去锁  值 0
thread-3加锁  值 1
thread-3去锁  值 0
thread-5加锁  值 1
thread-5去锁  值 0
thread-6加锁  值 1
thread-6去锁  值 0
发布了627 篇原创文章 · 获赞 535 · 访问量 359万+

猜你喜欢

转载自blog.csdn.net/boonya/article/details/103018544