zoukankan      html  css  js  c++  java
  • 原子类-Atomic*Array

    本文演示原子数组的使用方法,我们使用100自增线程和100自减线程对AtomicIntegerArray进行自增和自减操作,核对最终的结果是否为零。

    实例代码

      实例代码如下,最终结果为零。

      

    package com.yang.atomic;
    
    import java.util.concurrent.atomic.AtomicIntegerArray;
    
    /**
     * 本实例演示原子数组
     */
    public class AtomicIntegerArrayDemo {
        private static AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(100);
    
        public static void main(String[] args) throws InterruptedException {
            Increment incrementRunnable=new Increment(atomicIntegerArray);
            Decrement decrementRunnbale=new Decrement(atomicIntegerArray);
            Thread[] incrementThreads=new Thread[100];
            Thread[] decrementThreads=new Thread[100];
            for (int i = 0; i < 100; i++) {
                incrementThreads[i]=new Thread(incrementRunnable);
                decrementThreads[i]=new Thread(decrementRunnbale);
                incrementThreads[i].start();
                decrementThreads[i].start();
            }
    
            for (int i = 0; i < 100; i++) {
                incrementThreads[i].join();
                decrementThreads[i].join();
            }
    
    
            for (int i = 0; i < 100; i++) {
                System.out.println(atomicIntegerArray.get(i));
            }
            System.out.println("运行结束");
        }
    
    }
    
    class Increment implements Runnable {
    
        private AtomicIntegerArray array;
    
        public Increment(AtomicIntegerArray array) {
            this.array = array;
        }
    
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                array.getAndIncrement(i);
            }
        }
    }
    
    
    class Decrement implements Runnable {
    
        private AtomicIntegerArray array;
    
        public Decrement(AtomicIntegerArray array) {
            this.array = array;
        }
    
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                array.getAndDecrement(i);
            }
        }
    }
    

      

  • 相关阅读:
    laravel5.1--数据库操作
    coreseek (sphinx)+ Mysql + Thinkphp搭建中文搜索引擎详解
    apache配置虚拟主机
    PHP下利用PHPMailer
    linux中编译安装Apache、PHP、MySQL(上)
    MariaDB配置远程访问权限
    虚拟主机的配置
    PHP–图像XX因其本身有错无法显示
    apache重写中匹配?即查询时用到的字符
    nginx反向代理时的情况分析
  • 原文地址:https://www.cnblogs.com/cnxieyang/p/12760639.html
Copyright © 2011-2022 走看看