Java中使用Atomic*实现原子锁线程安全
生活随笔
收集整理的這篇文章主要介紹了
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?
總結
以上是生活随笔為你收集整理的Java中使用Atomic*实现原子锁线程安全的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浅谈小微企业智能化财务转型
- 下一篇: elementUi——适合于Vue的UI