zoukankan      html  css  js  c++  java
  • AtomicInteger的使用

    JDK API 1.7相关介绍

    可以用原子方式更新的 int 值。有关原子变量属性的描述,请参阅 java.util.concurrent.atomic 包规范。AtomicInteger 可用在应用程序中(如以原子方式增加的计数器),并且不能用于替换 Integer。但是,此类确实扩展了 Number,允许那些处理基于数字类的工具和实用工具进行统一访问。

    图片1

    图片2

    AtomicInteger 是线程安全的,多线程对同一个数加100次,结果一定是100. 相关代码示例:

    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.atomic.AtomicInteger;
    
    import javax.annotation.PostConstruct;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
    import org.springframework.stereotype.Component;
    
    /**
     * @ClassName: AtomicIntegerHandle 
     * @Description: AtomicInteger的使用
     * @author wasim
     * @create at 2015-8-12 下午8:44:51
     *  
     */
    @Component
    public class AtomicIntegerHandle {
    	
    	@Autowired
    	ThreadPoolTaskExecutor executor;
    	
    	@PostConstruct
    	public void handleQuestionKnowledge(){
    		
    		AtomicInteger atomicInteger = new AtomicInteger();
    		
    		int round = 15; //要执行的线程总数
    		
    		//导出文件 
    		executor.execute(new ExportStats(atomicInteger, round));
    		
    		//导出文件前,需要先循环下面12个线程
    		for(int i=0;i<round;i++){
    			executor.execute(new similarKnowledgeHandle(atomicInteger));
    		}
    		
    	}
    	
    	
    	public class similarKnowledgeHandle implements Runnable{
    		AtomicInteger atomicInteger;
    		
    		public similarKnowledgeHandle(AtomicInteger atomicInteger) {
    			this.atomicInteger =atomicInteger;
    		}
    		
    		@Override
    		public void run() {
    			System.out.println("do some thing....");
    			atomicInteger.getAndIncrement();
    			System.out.println(atomicInteger.get()); //显示当前计数
    		}
    	}
    	
    	
    	public class ExportStats implements Runnable{
    		
    		AtomicInteger atomicInteger;
    		int round;
    		
    		public ExportStats(AtomicInteger atomicInteger, int round) {
    			this.atomicInteger =atomicInteger;
    			this.round = round;
    		}
    		
    		@Override
    		public void run() {
    			try {
    				boolean flag = true;
    				while(flag){
    					if(atomicInteger.get() == round){
    						flag = false;
    						System.out.println("预处理完成,开始执行相关...");
    					} else {
    						System.out.println("wait...");
    						Thread.sleep(1000);
    					}
    				}
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		}
    		
    	}
    }
    
    http://www.wangxin123.com
  • 相关阅读:
    每天干攻防,都不会写驱动了
    SSD 坏了
    据说英雄联盟要出新皮肤了
    随便写点什么,证明我还活着,VS2010出现的问题
    ida 符号路径设置
    搭建一个自己的SVN服务器
    nginx+keepalived互为主主高可用配置
    nginx+keepalived主从高可用配置
    Lnamp的高级网站架构+动静分离+反向代理
    Nginx+PHP(FastCGI)高性能服务器加载redis+memcache模块
  • 原文地址:https://www.cnblogs.com/wangxin37/p/6397164.html
Copyright © 2011-2022 走看看