Java并发编程:同步锁、读写锁

2022-12-03,,,,

之前我们说过线程安全问题可以用锁机制来解决,即线程必要要先获得锁,之后才能进行其他操作。其实在 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<Integer> queue = new PriorityQueue<Integer>(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();
}
}

运行结果:

Thread- have the lock.
Thread- sleep Seconds.
Thread- have the lock.
Thread- release the lock.
Thread- release the lock.

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

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

三、一个读写锁的例子

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

package com.chanshuyi.class12;

import java.util.Random;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 读写锁实现读写互斥又不影响并发读取
* @author chenyr
* @time 2014-12-18 下午09:41:14
* All Rights Reserved.
*/
public class ReadWriteLock1 { public static void main(String args[]){
final MyQueue queue = new MyQueue();
for(int i = 0; i < 3; i++){
new Thread(){
public void run(){
while(true){ //不断读取数据
queue.get();
}
}
}.start(); new Thread(){
public void run(){
while(true){ //不断写入数据
queue.put(new Random().nextInt(10000));
}
}
}.start();
}
} } class MyQueue{
private Object data = null; //共享数据
private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); //写
public void put(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 void get(){
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锁,它允许多个线程同时读,但是同时有保证了写数据的时候不会有多个线程同时操作。也就是保证了程序读取的并发性能,又保证了线程的数据安全。

Java并发编程:同步锁、读写锁的相关教程结束。

《Java并发编程:同步锁、读写锁.doc》

下载本文的Word格式文档,以方便收藏与打印。