Java多线程锁

AQS

互斥锁,悲观锁

public class Demo1 {
    // 从0累加到1000 悲观锁
    static Integer num = 0;

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            Thread t = new Thread(() -> {
                while (num < 1000) {
                    synchronized (num.getClass()) {
                        if (num < 1000) {
                            System.out.println("thread name:" + Thread.currentThread().getName() + ":" + (++num));
                        }
                    }
                }
            });
            t.start();
        }
    }
}

乐观锁

不上锁

CAS

比较后交换,必须是原子性

package org.example.lock;

import java.util.concurrent.atomic.AtomicInteger;

public class Demo2 {
    // 从0累加到1000 乐观锁 无锁
    // 通过cpu的CAS实现同步的计数器
    static AtomicInteger num = new AtomicInteger(0);

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            Thread t = new Thread(() -> {
                while (num.get() < 1000) {
                    System.out.println("thread name:" + Thread.currentThread().getName() + ":" + num.incrementAndGet());
                }
            });
            t.start();
        }
    }
}

你可能感兴趣的:(Java,锁,多线程,java,开发语言)