AtomicInteger 并发加加


atomic并发加加 用的是硬件的cas 原子性操作 不会有并发问题 速度还快

下面的代码是从《深入理解java虚拟机弄出来的》


import java.util.concurrent.atomic.AtomicInteger;

public  class volatileTest {

    public static AtomicInteger race = new AtomicInteger();

    public static void increase(){
        race.incrementAndGet();
    }

    private static final int THREAD_COUNT = 20;

    public static void main(String[] args) throws InterruptedException {

        Thread[] threads = new Thread[THREAD_COUNT];

        for (int i = 0; i < THREAD_COUNT; i++) {
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0;i<10000;i++){
                        increase();
                    }
                }
            });

            threads[i].start();
        }

        System.out.println(Thread.activeCount());
//这里如果改打 结果就不准确了
while (Thread.activeCount()>1){ Thread.yield(); } System.out.println(race); } }

 

atomic并发加是准确的

我直接跑不准确是因为主线程跑完了,其他加的线程还没跑完
改为下面代码
import java.util.concurrent.atomic.AtomicInteger;

public  class volatileTest {

    public static AtomicInteger race = new AtomicInteger();

    public static void increase(){
        race.incrementAndGet();
    }

    private static final int THREAD_COUNT = 20;

    public static void main(String[] args) throws InterruptedException {

        Thread[] threads = new Thread[THREAD_COUNT];

        for (int i = 0; i < THREAD_COUNT; i++) {
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0;i<10000;i++){
                        increase();
                    }
                }
            });

            threads[i].start();
        }

        System.out.println(Thread.activeCount());
        while (Thread.activeCount()>10){
            //这里如果加race  那么只会跑一次 不知道什么情况
            System.out.println("来了"+"此时是:"+race);
            //System.out.println("来了"+"此时是:");
            Thread.yield();
        }


        System.out.println(race);
        Thread.sleep(200);
        System.out.println(race);
    }
}

  

先这样吧 我的水平太差里

posted @ 2023-03-13 14:54  霸王龙168  阅读(50)  评论(0)    收藏  举报