码迷,mamicode.com
首页 > 其他好文 > 详细

锁对象Lock

时间:2017-09-03 00:29:18      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:不能   效果   length   get   ati   ted   san   trace   准备   

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();// 释放读锁  

}  

}  

}  

锁对象Lock

标签:不能   效果   length   get   ati   ted   san   trace   准备   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!