public void tryLock(){
Lock lock = new ReentrantLock();
if (lock.tryLock()) { //尝试获取锁,如果拿到用锁,拿不到转而其它操作
try {
// manipulate protected state
} finally {
lock.unlock();
}
} else {
// perform alternative actions
}
}
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
}
}
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();//释放锁
}
}
}