多线程的问题和CAS

2020-10-29  本文已影响0人  叫我C30混凝土

多线程的问题

//竞争条件示例:
    private static int counter = 0;

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

        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                counter++;
            }).start();
        }
        Thread.sleep(100);
        System.out.println(counter);
    }

控制台结果:
95
- 协同:同时、随机执行的线程,如何协同工作?
      - 解决问题的办法:
      1. java原生实现
       1.1 同步: synchronized
       1.2 协同: wait() / notify() / notifyAll()

CAS(compare and swap)

private static AtomicInteger counter = new AtomicInteger();

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

        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                increment();
            }).start();
        }
        Thread.sleep(100);
        System.out.println(counter);
    }

    private static void increment(){
        counter.getAndIncrement();
    }
private static int counter = 0;

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

        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                increment();
            }).start();
        }
        Thread.sleep(100);
        System.out.println(counter);
    }

    private synchronized static void increment(){ //synchronized 悲观锁
        counter++;
    }

附:
mutex = lock
java.util.Collections.SynchronizedMap#mutex
来源于: mutual(共享) + exclusive(排他)

上一篇 下一篇

猜你喜欢

热点阅读