1 ReentrantReadWriteLock :(读写锁、写写锁互斥,读读锁共享,常用于缓存如terrocotta)
2 ReentrantLock :(可轮询的、定时的、可中断 lock() unlock())结合Condition将线程放入相应阻塞队列,比较灵活 Condition notFull = lock.newCondition();
3 Synchronized (单一对象锁监视器) 只能单一线程阻塞队列
一:可轮询的、定时的、可中断的锁获取操作
(1)可轮询
public void tryLock(){
Lock lock = new ReentrantLock();
if (lock.tryLock()) { //尝试获取锁,如果拿到用锁,拿不到转而其它操作
try {
// manipulate protected state
} finally {
lock.unlock();
}
} else {
// perform alternative actions
}
}
(2)定时锁
public void tryTimeLock() throws InterruptedException{
Lock lock = new ReentrantLock();
if (lock.tryLock(50, TimeUnit.SECONDS)) { //如果线程50秒内未获取锁,则超时返回
try {
// manipulate protected state
} finally {
lock.unlock();
}
} else {
// perform alternative actions
}
}
(3)可中断锁
public void lockInterruptibly() throws InterruptedException{
Lock lock = new ReentrantLock();
try{
lock.lockInterruptibly(); //优先响应时间中断,而不是重新获取锁
// manipulate protected state
lock.unlock();
}
catch (InterruptedException e){
}
}
二:公平队列或非块结构锁
public class ReentrantFairLock {
private volatile long count = 0;// 保持内存可见性,各线程立可见
private Lock lock;
public ReentrantFairLock() {
// 使用非公平锁,true就是公平锁
lock = new ReentrantLock(true);//公平锁
//所谓公平锁就是让等待最长的线程最早获得该锁(获得锁的顺序和申请锁的顺序是一致的),性能比非公平锁性能差
//lock = new ReentrantLock(false);//非公平锁(无参数默认)
}
public long getValue() {
return count;
}
public void increment() {
lock.lock(); // 保持操作原子性
try {
count++;
} finally {
lock.unlock();
}
}
}
public class ConditionBoundedBuffer{
final Lock lock = new ReentrantLock();//实例化一个锁对象
final Condition notFull = lock.newCondition(); //实例化两个condition(多路等待)
final Condition notEmpty = lock.newCondition();
final Object[] items = new Object[100];//初始化一个长度为100的队列
int putptr, takeptr, count;
public void put(Object x) throws InterruptedException {
lock.lock();//获取锁
try {
while (count == items.length) //放线程队列阻塞,唤醒取线程队列
notFull.await();//当计数器count等于队列的长度时,不能在插入,因此等待,线程阻塞在notFull队列
items[putptr] = x; //将对象放入putptr索引处
if (++putptr == items.length) putptr = 0;//当索引长度等于队列长度时,将putptr置为0 原因是,不能越界插入
++count;//没放入一个对象就将计数器加1
notEmpty.signal();//一旦插入就唤醒取数据线程
} finally {
lock.unlock();//最后释放锁
}
}
public Object take() throws InterruptedException{
lock.lock();//获取锁
try {
while (count == 0) //取线程队列阻塞,唤醒放线程队列
notEmpty.await();
Object x = items[takeptr]; //取得takeptr索引处对象
if (++takeptr == items.length) takeptr = 0;//当takeptr达到队列长度时,从零开始取
--count;//每取一个讲计数器减1
notFull.signal();//枚取走一个就唤醒存线程
return x;
} finally {
lock.unlock();//释放锁
}
}
}
ReentrantReadWriteLock读写锁:(针对不同操作可以提供不同读或写锁 --读写锁、写写锁之间互斥。读读锁共享)
写锁和其它任何锁互斥,读锁可以和其它读锁共用,读写锁一般可用于缓存设计
1)获取读锁
2)(cachedList == null)释放读锁,获取写锁
3)填充数据
4)释放写锁前获取读锁,然后释放写锁
5)最终是释放读锁
public class ReadWriteLockTest {
public static void main(String[] args) {
final Queue3 q3 = new Queue3();
for(int i=0;i<3;i++)
{
new Thread(){
public void run(){
while(true){ //三个线程读
q3.get();
}
}
}.start();
new Thread(){
public void run(){
while(true){
q3.put(new Random().nextInt(10000)); //三个线程写
}
}
}.start();
}
}
}
class Queue3{
private Object data = null;//共享数据,只能有一个线程能写该数据,但可以有多个线程同时读该数据。
ReadWriteLock rwl = new ReentrantReadWriteLock();//实现接口ReadWriteLock
public void get(){
rwl.readLock().lock(); //两个线程读锁可以同时进入该读锁临界区内,但是排斥写锁
try {
System.out.println(Thread.currentThread().getName() + " be ready to read data!");
Thread.sleep((long)(Math.random()*1000));
System.out.println(Thread.currentThread().getName() + "have read data :" + data);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
rwl.readLock().unlock();
}
}
public void put(Object data){
rwl.writeLock().lock(); //写锁排斥其它任何线程锁进入该写锁临界区
try {
System.out.println(Thread.currentThread().getName() + " be ready to write data!");
Thread.sleep((long)(Math.random()*1000));
this.data = data;
System.out.println(Thread.currentThread().getName() + " have write data: " + data);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
rwl.writeLock().unlock();
}
}
}
ReentrantLock(重入锁):
public class ReentrantlockTest {
public static void main(String[] args) {
ExecutorService excuteService = Executors.newCachedThreadPool();
final Bussiness bussiness =new Bussiness();
for(int i=0;i<3;i++){
excuteService.submit(new Runnable(){
@Override
public void run() {
bussiness.service();
}
});
}
}
}
class Bussiness{
int count =0;
Lock lock = new ReentrantLock();//实现接口Lock
public void service(){
lock.lock(); //上锁
try{
count++;
System.out.println("count is :"+count);
}catch(Exception e){}
finally{
lock.unlock();//解锁(出现异常防止死锁)
}
}
}