多线程--原子类理解

package cn.stu;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {

	public static AtomicInteger  index = new AtomicInteger(0);
	public static int count; 
	
	
	 
	public static void main(String[] args) throws InterruptedException {
		  
		
		final CountDownLatch latch = new CountDownLatch(10000); 
		ExecutorService service = Executors.newFixedThreadPool(10000);
		for(int i = 0; i<10000;i++){
			  
			 service.submit(new Runnable() {
				
				@Override
				public void run() {
					  //  使用非阻塞算法来实现并发控制。 
					  //  如果我们用 Lock的形式需要的还是阻塞式来处理,一条线程形式来一次加1的模式。
					 index.getAndIncrement(); 
					 count++;
					 latch.countDown();
				}
			});
		}
		
		latch.await(); 
		
        System.out.println("运行结果:---->"+index.intValue()+"-----普通数据--->"+count);
        
        service.shutdown();
	}
	
	

}

运行结果:

运行结果:---->10000-----普通数据--->9996



前面的10000是不会改变的。 后面的9996会进行改变。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值