一、多线程

1.为什么使用多线程: (1)安全 (2)效率

2.多线程使用场景: (1)需要执行比较耗时的操作 (2)需要异步处理的业务(比如阻塞) 3.使用多线程要考虑的因素: (1)执行的代码任务量 (2)系统资源 (3)执行任务的数量

二、线程间竞争对象锁的过程

三、synchronized关键字

1.synchronized的作用: 通过线程间的同步互斥达到线程安全的三大特性(原子性、可见性、有序性) 2.synchronized执行效率: (1)如果线程数量越多,性能下降的越快 (2)同步代码执行时间越快。性能相对来说,下降越快 3.synchronized实现原理: monitor机制:monitorenter、monitorexit,计数器 4.synchronized的锁机制: (1)乐观锁: (2)悲观锁: (3)CAS Compare and Swap,比较并交换(原始值、修改值、预期值、版本号)---属于乐观锁 CAS的应用: java.util.concurrent.atomic的实现原理就是CAS 举例:

public class CASTest {
    public static void main(String[] args) {
        //设定初始值为5
        AtomicInteger atomicInteger=new AtomicInteger(5);
        //main线程在工作一段时间后,要将自己的工作内存的值写进主内存
        //main的期望值是5,如果期望值与atomicInteger的值一样,就更新我指定的值,
        System.out.println(atomicInteger.compareAndSet(5, 2020) + "值为" + atomicInteger.get());
        System.out.println(atomicInteger.compareAndSet(2020, 21) + "值是:" + atomicInteger.get());
        System.out.println(atomicInteger.compareAndSet(2020, 21) + "值是:" + atomicInteger.get());
    }
}

5.synchronized的优化方案: