多线程--原子类理解

来源:互联网 发布:手机移动数据自动开启 编辑:程序博客网 时间:2024/05/21 01:28
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() {@Overridepublic 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
原创粉丝点击