Java原子更新类

Posted 水田如雅

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java原子更新类相关的知识,希望对你有一定的参考价值。

 @Test
    public void test6() throws Exception 
        AtomicInteger value = new AtomicInteger(0);
        CyclicBarrier cyclicBarrier = new CyclicBarrier(100);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 100; i++) 
            executorService.submit(new Runnable() 
                @SneakyThrows
                @Override
                public void run() 
                    System.out.println(value.getAndIncrement());
                    cyclicBarrier.await();
                
            );
        
        cyclicBarrier.await();
        System.out.println("value" + value);
    

    @Test
    public void test7() throws Exception 
        int[] arr = 0, 1, 2;
        AtomicIntegerArray valueArr = new AtomicIntegerArray(arr);
        CyclicBarrier barrier = new CyclicBarrier(100);
        for (int i = 0; i < 100; i++) 
            new Thread() 
                @SneakyThrows
                @Override
                public void run() 
                    valueArr.getAndAdd(0, 1);
                    barrier.await();
                
            .start();
        
        barrier.await();
        System.out.println(JSONObject.toJSONString(valueArr.get(0)));
    


    @Test
    public void test8() throws Exception 
        Person person = new Person("lhc", 0);
        AtomicReference<Person> personAtomicReference = new AtomicReference<>(person);
        CyclicBarrier barrier = new CyclicBarrier(100);
        for (int i = 0; i < 100; i++) 
            new Thread() 
                @SneakyThrows
                @Override
                public void run() 
                    System.out.println(personAtomicReference.compareAndSet(person, new Person("lhc", 11)));
                    barrier.await();
                
            .start();
        
        barrier.await();
        System.out.println(JSONObject.toJSONString(personAtomicReference.get().getAge()));
    

    @Test
    public void test9() throws Exception 
        Person person = new Person("lhc", 0);
        AtomicIntegerFieldUpdater<Person> updater = AtomicIntegerFieldUpdater.newUpdater(Person.class, "age");
        CyclicBarrier barrier = new CyclicBarrier(100);
        for (int i = 0; i < 100; i++) 
            new Thread() 
                @SneakyThrows
                @Override
                public void run() 
                    updater.addAndGet(person, 1);
                    barrier.await();
                
            .start();
        
        barrier.await();
        System.out.println(JSONObject.toJSONString(updater.get(person)));

    

以上是关于Java原子更新类的主要内容,如果未能解决你的问题,请参考以下文章

Java学习笔记—多线程(原子类,java.util.concurrent.atomic包,转载)

Java原子更新类

Java原子更新类

Java并发编程的艺术 -- 原子操作类和并发工具类(第七八章)

Java原子变量类需要注意的问题