您的位置:首页 > 其它

多线程--原子类理解

2016-10-27 14:19 225 查看
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会进行改变。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  AtomicInteger