(1)安全
(2)效率
(1)需要执行比较耗时的操作
(2)需要异步处理的业务(比如阻塞)
(1)执行的代码任务量
(2)系统资源
(3)执行任务的数量
通过线程间的同步互斥达到线程安全的三大特性(原子性、可见性、有序性)
(1)如果线程数量越多,性能下降的越快
(2)同步代码执行时间越快。性能相对来说,下降越快
monitor机制:monitorenter、monitorexit,计数器
(1)乐观锁:
(2)悲观锁:
(3)CAS Compare and Swap,比较并交换(原始值、修改值、预期值、版本号)—属于乐观锁
java.util.concurrent.atomic的实现原理就是CAS
举例:
public class CASTest {public static void main(String[] args) {//设定初始值为5AtomicInteger 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());}
}