java同步锁案例_Java并发编程:同步锁、读写锁

之前我们说过线程安全问题可以用锁机制来解决,即线程必要要先获得锁,之后才能进行其他操作。其实在 Java 的 API 中有这样一些锁类可以提供给我们使用,与其他对象作为锁相比,它们具有更强大的功能。

Java 中的锁有两种,分别是:1)同步锁 2)读写锁

一、同步锁

同步锁(ReentrantLock)类似于 synchronize 代码块中传入的那个锁对象,可以用于进行线程同步。ReentrantLock.lock() 方法用于锁定对象,而 ReentrantLock.unlock 用于释放锁对象。

public class SynLockDemo {

static final ReentrantLock lock = new ReentrantLock(); //同步锁

public static void main(String args[]) {

//线程1

new Thread(){

public void run() {

lock.lock();

System.out.println(Thread.currentThread().getName() + " have the lock.");

try {

System.out.println(Thread.currentThread().getName() + " sleep 3 Seconds.");

Thread.sleep(3000);

} catch (InterruptedException e) {

e.printStackTrace();

}

lock.unlock();

System.out.println(Thread.currentThread().getName() + " release the lock.");

}

}.start();

//线程2

new Thread(){

public void run() {

lock.lock();

System.out.println(Thread.currentThread().getName() + " have the lock.");

lock.unlock();

System.out.println(Thread.currentThread().getName() + " release the lock.");

}

}.start();

}

}

可以看到线程 1 即使休眠了 3 秒,线程 2 也还是会等到线程 1 执行完才会继续执行。

ReentrantLock 除了可以实现基本的线程同步阻塞之外,还可以配合 Condition 类使用,实现线程通信。我们可以用 Condition 来实现生产者 - 消费者问题:

public class Test {

private int queueSize = 10;

private PriorityQueue queue = new PriorityQueue(queueSize);

private Lock lock = new ReentrantLock();

private Condition notFull = lock.newCondition();

private Condition notEmpty = lock.newCondition();

public static void main(String[] args)  {

Test test = new Test();

Producer producer = test.new Producer();

Consumer consumer = test.new Consumer();

producer.start();

consumer.start();

}

class Consumer extends Thread{

@Override

public void run() {

consume();

}

private void consume() {

while(true){

lock.lock();

try {

while(queue.size() == 0){

try {

System.out.println("队列空,等待数据");

notEmpty.await();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

queue.poll();                //每次移走队首元素

notFull.signal();

System.out.println("从队列取走一个元素,队列剩余"+queue.size()+"个元素");

} finally{

lock.unlock();

}

}

}

}

class Producer extends Thread{

@Override

public void run() {

produce();

}

private void produce() {

while(true){

lock.lock();

try {

while(queue.size() == queueSize){

try {

System.out.println("队列满,等待有空余空间");

notFull.await();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

queue.offer(1);        //每次插入一个元素

notEmpty.signal();

System.out.println("向队列取中插入一个元素,队列剩余空间:"+(queueSize-queue.size()));

} finally{

lock.unlock();

}

}

}

}

}

二、读写锁

ReentrantReadWriteLock 是 Java 中用于控制读写的一个类。lock.readLock 方法用于获取一个读锁,而 lock.writeLock 方法用于获取一个写锁。读锁允许多个线程进行读取数据操作,但不允许修改操作。而写锁则不允许其他线程进行读和写操作。

我们改写下上面的 Demo,将 ReentrantLock 换成 ReentrantReadWriteLock,并锁上读锁

public class ReadWriteLockDemo {

static final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); //同步锁

public static void main(String args[]) {

//线程1

new Thread(){

public void run() {

// rwl.readLock().lock();

rwl.writeLock().lock();

System.out.println(Thread.currentThread().getName() + " have the lock.");

try {

System.out.println(Thread.currentThread().getName() + " sleep 3 Seconds.");

Thread.sleep(3000);

} catch (InterruptedException e) {

e.printStackTrace();

}

rwl.writeLock().unlock();

System.out.println(Thread.currentThread().getName() + " release the lock.");

}

}.start();

//线程2

new Thread(){

public void run() {

rwl.writeLock().lock();

System.out.println(Thread.currentThread().getName() + " have the lock.");

rwl.writeLock().unlock();

System.out.println(Thread.currentThread().getName() + " release the lock.");

}

}.start();

}

}

运行结果:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

Thread-0 have the lock.

Thread-0 sleep 3Seconds.

Thread-1 have the lock.

Thread-1 release the lock.

Thread-0 release the lock.

View Code

从结果可以看出,线程0获取到锁并不会阻塞线程1获取锁,因此可以知道读锁其实是并发的。

如果我们把上面的 rwl.readLock() 换成 rwl.writeLock(),那么线程1就会等到线程0释放锁之后才会继续执行。

三、一个读写锁的例子

读写锁与一般的锁的不同之处就是它有两种锁,分别是读锁(ReadLock)和写锁(WriteLock)。当我们锁上读锁的时候,其他线程也可以读取对象的数据,但是不能修改。但当我们锁上写锁的时候,其他线程就无法进行读操作,也没办法进行写操作。这样就即保证了读取数据的高并发,又保证了线程的数据安全。下面我们来看一个例子:

packagecom.chanshuyi.class12;

importjava.util.Random;

importjava.util.concurrent.locks.ReentrantReadWriteLock;

/**

* 读写锁实现读写互斥又不影响并发读取

* @author chenyr

* @time 2014-12-18 下午09:41:14

* All Rights Reserved.

*/

public classReadWriteLock1 {

public static voidmain(String args[]){

final MyQueue queue = newMyQueue();

for(int i = 0; i < 3; i++){

newThread(){

public voidrun(){

while(true){ //不断读取数据

queue.get();

}

}

}.start();

newThread(){

public voidrun(){

while(true){ //不断写入数据

queue.put(new Random().nextInt(10000));

}

}

}.start();

}

}

}

classMyQueue{

private Object data = null; //共享数据

private ReentrantReadWriteLock rwl = newReentrantReadWriteLock();

//写

public voidput(Object obj){

rwl.writeLock().lock();

System.out.println(Thread.currentThread().getName() + " is ready to write !");

try{

Thread.sleep((long)(Math.random() * 1000)); //因为是不断写入,所以必须让线程休眠,避免CPU耗尽

}catch(Exception e){

e.printStackTrace();

}

this.data =obj;

System.out.println(Thread.currentThread().getName() + " has complte write :" + this.data);

rwl.writeLock().unlock();

try{

Thread.sleep(1000); //让写进程休眠长一点时间,否则会导致读取进程很久都无法读取数据。

}catch(Exception e){

e.printStackTrace();

}

}

//读

public voidget(){

rwl.readLock().lock();

System.out.println(Thread.currentThread().getName() + " is ready to read !");

try{

Thread.sleep((long)(Math.random() * 1000)); //因为是不断读取,所以必须让线程休眠,避免CPU耗尽

}catch(Exception e){

e.printStackTrace();

}

System.out.println(Thread.currentThread().getName() + "has read the value :" + this.data);

rwl.readLock().unlock();

}

}

在上面这个例子中,我们创建了3个读数据进程以及3个写数据进程,不断取出、写入MyQueue中的数据。在MyQueue调用读取数据get()方法时,锁上读锁,在调用写数据put()方法时,锁上写锁。下面是一部分的运行结果:

1 Thread-1 is ready to read !

2 Thread-3 is ready to read !

3 Thread-5 is ready to read !

4 Thread-1has read the value :null

5 Thread-3has read the value :null

6 Thread-5has read the value :null

7 Thread-6 is ready to write !

8 Thread-6 has complte write :4138

9 Thread-4 is ready to write !

10 Thread-4 has complte write :6158

11 Thread-2 is ready to write !

12 Thread-2 has complte write :3333

13 Thread-1 is ready to read !

14 Thread-5 is ready to read !

15 Thread-3 is ready to read !

16 Thread-3has read the value :3333

17 Thread-3 is ready to read !

18 Thread-5has read the value :3333

19 Thread-5 is ready to read !

20 Thread-1has read the value :3333

21 Thread-1 is ready to read !

22 Thread-3has read the value :3333

23 Thread-1has read the value :3333

24 Thread-5has read the value :3333

25 Thread-6 is ready to write !

26 Thread-6 has complte write :6568

27 Thread-4 is ready to write !

28 Thread-4 has complte write :4189

29 Thread-3 is ready to read !

30 Thread-1 is ready to read !

31 Thread-3has read the value :4189

32 Thread-1has read the value :4189

从上面的运行结果我们可以看到:1-3行,13-15行出现了多个线程同时读取数据的情况。

观察输出结果,可以发现在写入数据的时候(如 7 - 12 行),即使有多次连续写入数据,但是都是等待一个线程写入结束后,另一个线程才开始写入数据的,没有出现同时多个线程写入的情况。这就说明写锁不允许多个线程同时写,也不允许读。

这就是读写锁的一个非常重要的应用,比起synchronized或lock锁,它允许多个线程同时读,但是同时有保证了写数据的时候不会有多个线程同时操作。也就是保证了程序读取的并发性能,又保证了线程的数据安全。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值