锁
1、分类:
- 乐观锁
- 悲观锁
A. 共享锁
B. 排他锁 - 公平锁,非公平锁
2、悲观排他非公平锁
1) 同步方法
public Sychronized void show(){
this.wait(int millisec)
....
this.nodify();/this.notifyAll()
}
锁为当前对象
2)同步代码块
Sychronized(locker){
locker.wait(int millisec)
locker.nodify();/locker.notifyAll()
}
3、
Lock lock = new ReentrantLock(false);//悲观排他true公平,false不公平
Lock lock = new ReentrantLock();//悲观排他非公平锁
Condition cond = lock.newCondition();
try{
lock.lockInterruptibly();
cond.await(int millisec);
cond.signal();/cond.signalAll();
}catch(…){
…
}finally{
lock.unlock();
}
4、读写锁
ReentrantReadWriteLock rw = new ReentrantReadWriteLock(true);
ReentrantReadWriteLock.ReadLock readLock = rw.readLock();
ReentrantReadWriteLock.WriteLock writeLock = rw.writeLock();