Lock和Condition

锁对象Lock

Lock 实现提供了比使用synchronized 方法和语句可获得的更广泛的锁定操作,它能以更优雅的方式处理线程同步问题:

public class LockTest {  

publicstaticvoid main(String[] args) {  

final Outputter1 output = new Outputter1();  

new Thread() {  

publicvoid run() {  

output.output("zhangsan");  

};  

}.start();        

new Thread() {  

publicvoid run() {  

output.output("lisi");  

};  

}.start();  

}  

}  

class Outputter1 {  

private Lock lock = new ReentrantLock();// 锁对象  

publicvoid output(String name) {  

// TODO 线程输出方法  

lock.lock();// 得到锁  

try {  

for(int i = 0; i < name.length(); i++) {  

System.out.print(name.charAt(i));  

}  

finally {  

lock.unlock();// 释放锁  

}  

}  

}  

        这样就实现了和sychronized一样的同步效果,需要注意的是,用sychronized修饰的方法或者语句块在代码执行完之后锁自动释放,而用Lock需要我们手动释放锁,所以为了保证锁最终被释放(发生异常情况),要把互斥区放在try内,释放锁放在finally内。

        如果说这就是Lock,那么它不能成为同步问题更完美的处理方式,下面要介绍的是读写锁(ReadWriteLock),我们会有一种需求,在对数据进行读写的时候,为了保证数据的一致性和完整性,需要读和写是互斥的,写和写是互斥的,但是读和读是不需要互斥的,这样读和读不互斥性能更高些。

class Data {      

privateint data;// 共享数据  

private ReadWriteLock rwl = new ReentrantReadWriteLock();     

publicvoid set(int data) {  

rwl.writeLock().lock();// 取到写锁  

try {  

System.out.println(Thread.currentThread().getName() + "准备写入数据");  

try {  

Thread.sleep(20);  

catch (InterruptedException e) {  

e.printStackTrace();  

}  

this.data = data;  

System.out.println(Thread.currentThread().getName() + "写入" + this.data);  

finally {  

rwl.writeLock().unlock();// 释放写锁  

}  

}     

publicvoid get() {  

rwl.readLock().lock();// 取到读锁  

try {  

System.out.println(Thread.currentThread().getName() + "准备读取数据");  

try {  

Thread.sleep(20);  

catch (InterruptedException e) {  

e.printStackTrace();  

}  

System.out.println(Thread.currentThread().getName() + "读取" + this.data);  

finally {  

rwl.readLock().unlock();// 释放读锁  

}  

}  

}  

Java Condition

在Condition中,用await()替换wait(),用signal()替换notify(),用signalAll()替换notifyAll(),传统线程的通信方式,Condition都可以实现,这里注意,Condition是被绑定到Lock上的,要创建一个Lock的Condition必须用newCondition()方法。

class BoundedBuffer {  

final Lock lock = new ReentrantLock();//锁对象  

final Condition notFull  = lock.newCondition();//写线程条件   

final Condition notEmpty = lock.newCondition();//读线程条件   

final Object[] items = new Object[100];//缓存队列  

int putptr/*写索引*/, takeptr/*读索引*/, count/*队列中存在的数据个数*/;  

publicvoid put(Object x) throws InterruptedException {  

lock.lock();  

try {  

while (count == items.length)//如果队列满了   

notFull.await();//阻塞写线程  

items[putptr] = x;//赋值   

if (++putptr == items.length) putptr = 0;//如果写索引写到队列的最后一个位置了,那么置为0  

++count;//个数++  

notEmpty.signal();//唤醒读线程  

finally {  

lock.unlock();  

}  

}  

public Object take() throws InterruptedException {  

lock.lock();  

try {  

while (count == 0)//如果队列为空  

notEmpty.await();//阻塞读线程  

Object x = items[takeptr];//取值   

if (++takeptr == items.length) takeptr = 0;//如果读索引读到队列的最后一个位置了,那么置为0  

--count;//个数--  

notFull.signal();//唤醒写线程  

return x;  

finally {  

lock.unlock();  

}  

}   

}  

原文地址:https://www.cnblogs.com/m2492565210/p/7468380.html