zoukankan      html  css  js  c++  java
  • AtomicStampedReference

    package japan.example.test;
    
    import java.io.IOException;
    import java.util.concurrent.atomic.AtomicStampedReference;
    
    public class FinalTest {
    
        public final static AtomicStampedReference<String> ATOMIC_REFERENCE = new AtomicStampedReference<String>("abc", 0);
    
        public static void main(String[] args) throws IOException {
            for (int i = 0; i < 100; i++) {
                final int num = i;
                final int stamp = ATOMIC_REFERENCE.getStamp();
                new Thread(() -> {
                    try {
                        Thread.sleep(Math.abs((int) (Math.random() * 100)));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (ATOMIC_REFERENCE.compareAndSet("abc", "abc2", stamp, stamp + 1)) {
                        System.out.println("我是线程:" + num + ",我获得了锁进行了对象修改!");
                    }
                }).start();
            }
    
            new Thread(() -> {
                int stamp = ATOMIC_REFERENCE.getStamp();
                while (ATOMIC_REFERENCE.compareAndSet("abc2", "abc", stamp, stamp + 1)) {
                    System.out.println("已经改回为原始值!");
                }
            }).start();
    
            // System.in.read();
        }
    
    }
  • 相关阅读:
    文件进阶
    文件及文件操作
    字符编码
    集合
    数据类型之字典
    数据类型之列表,元组
    数据类型之数字,字符串
    for 循环语句
    while 循环语句
    深浅拷贝
  • 原文地址:https://www.cnblogs.com/jpit/p/8288299.html
Copyright © 2011-2022 走看看