Java并发之重入锁+读写锁

Java多线程中,除了sychronized关键字实现多线程之间同步互斥操作,其实还有另外一种高效的机制去完成”同步互斥”操作。即Lock对象,比synchronized关键字更为强大功能,并且有嗅探锁定,多路分支等功能。

重入锁
默认非公平锁

  public ReentrantLock() {
        sync = new NonfairSync();
    }

常用方法:
这里写图片描述

private Lock lock = new ReentrantLock();
 public void method1(){
        try {
             //加锁
            lock.lock();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "进入method1..");
            Thread.sleep(1000);
            System.out.println("当前线程:" + Thread.currentThread().getName() + "退出method1..");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //一定要释放锁,否则其他线程拥有无法获取
            lock.unlock();
        }
    }

以前使用synchronized 关键字进行多线程协同工作时,需要使用Object 等wait()阻塞释放锁,notify()唤醒,不释放锁等进行配合使用。
使用Lock时可以使用新的等待/通知类,Condition,Condition一定是针对某一把固定的锁,也就是说,只有在有锁的基础上才会产生Condition

/**
 * @author zhanghuilong
 * @version V1.0
 * @desc
 * @since 2018/01/16
 */
public class UseCondition {

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void method1(){
        try {
            lock.lock();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "进入等待状态..");
            Thread.sleep(3000);
            System.out.println("当前线程:" + Thread.currentThread().getName() + "释放锁..");
            //释放锁,类似于 Object wait,阻塞于此
            condition.await();
            System.out.println("当前线程:" + Thread.currentThread().getName() +"继续执行...");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void method2(){
        try {
            lock.lock();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "进入..");
            Thread.sleep(3000);
            System.out.println("当前线程:" + Thread.currentThread().getName() + "发出唤醒..");
            //不释放锁类,似于Object notify
            condition.signal();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "没有释放锁");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {

        final UseCondition uc = new UseCondition();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                uc.method1();
            }
        }, "t1");
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                uc.method2();
            }
        }, "t2");
        t1.start();

        t2.start();
    }



}

result:
这里写图片描述

读写锁:核心思想实现读写分离,高并发下特别适合 读多写少的场景。
之前的synchronized关键字和ReentrantLock 同一时间只能有一个线程进行访问被锁定的代码,读写锁的机制则不是,本质上分为两把锁,读锁和写锁,在读锁情况下,多个线程可以并发访问资源,只有当是写锁时只能一个一个的顺序执行。
口诀:读读共享,写写互斥,读写互斥。

/**
 * @author zhanghuilong
 * @version V1.0
 * @desc
 * @since 2018/01/16
 */
public class UseReentrantReadWriteLock {
    private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    private ReentrantReadWriteLock.ReadLock readLock = rwLock.readLock();
    private ReentrantReadWriteLock.WriteLock writeLock = rwLock.writeLock();

    public void read() {
        try {
            readLock.lock();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "进入...");
            Thread.sleep(3000);
            System.out.println("当前线程:" + Thread.currentThread().getName() + "退出...");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
        }
    }

    public void write() {
        try {
            writeLock.lock();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "进入...");
            Thread.sleep(3000);
            System.out.println("当前线程:" + Thread.currentThread().getName() + "退出...");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
    }

    public static void main(String[] args) {

        final UseReentrantReadWriteLock urrw = new UseReentrantReadWriteLock();

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                urrw.read();
            }
        }, "t1");
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                urrw.read();
            }
        }, "t2");
        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                urrw.write();
            }
        }, "t3");
        Thread t4 = new Thread(new Runnable() {
            @Override
            public void run() {
                urrw.write();
            }
        }, "t4");

        t1.start();
        t2.start();

        //      t1.start(); // R
        //      t3.start(); // W

        t3.start();
        t4.start();

    }

}

result:t1 t2同时进入。。

这里写图片描述

猜你喜欢

转载自blog.csdn.net/java_huilong/article/details/79070311