JAVA线程安全计数器

通过CAS的方式实现计数器

代码有测试用例,最简单的就是最可靠的。

package Offer.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class Counter {
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public int getCount(){
        safeCount();
        return atomicInteger.get();
    }

    private void safeCount(){
        for(;;){
            int i =atomicInteger.get();
            boolean suc = atomicInteger.compareAndSet(i, ++i);
            if(suc){
                break;
            }
        }
    }


    //====================下面代码用来测试线程安全
    private int i =0;
    private void unSafeCount(){
        i++;
    }

    public static void main(String[] args) {
        final Counter cas = new Counter();
        List list = new ArrayList<>();
        long start = System.currentTimeMillis();
        for (int j = 0; j < 100; j++) {
            Thread thread = new Thread(() -> {
                for (int i = 0; i < 100; i++) {
                    cas.safeCount();
                    cas.unSafeCount();
                }
            });
            list.add(thread);
        }
        for(Thread t: list){
            t.start();
        }
        for (Thread t : list) {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(cas.i);
        System.out.println(cas.atomicInteger.get());
        System.out.println(System.currentTimeMillis() - start);
    }
}

 

你可能感兴趣的:(java)