Java 8新特性探究(十)StampedLock将是解决同步问题的新宠
Java8就像一个宝藏,一个小的API改进,也足与写一篇文章,比如同步,一直是多线程并发编程的一个老话题,相信没有人喜欢同步的代码,这会降低应用的吞吐量等性能指标,最坏的时候会挂起死机,但是即使这样你也没得选择,因为要保证信息的正确性。所以本文决定将从synchronized、Lock到Java8新增的StampedLock进行对比分析,相信StampedLock不会让大家失望。 synchronized 在java5之前,实现同步主要是使用synchronized。它是 Java语言的关键字,当它用来修饰一个方法或者一个代码块的时候,能够保证在同一时刻最多只有一个线程执行该段代码。 有四种不同的同步块: 实例方法 静态方法 实例方法中的同步块 静态方法中的同步块 大家对此应该不陌生,所以不多讲了,以下是代码示例 synchronized(this) // do operation } 小结: 在多线程并发编程中Synchronized一直是元老级角色,很多人都会称呼它为重量级锁,但是随着Java SE1.6对Synchronized进行了各种优化之后,性能上也有所提升。 Lock 它是Java 5在java.util.concurrent.locks新增的一个API。 Lock是一个接口,核心方法是lock(),unlock(),tryLock()