读写锁,await和signa

Posted 512178509

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了读写锁,await和signa相关的知识,希望对你有一定的参考价值。

package com.fh.interview;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 *
 * 支持重入性,能够对共享资源重复加锁
 * 支持公平锁和非公平锁
 *
 * 公平锁:锁的获取顺序应该满足绝对的时间顺序,FIFO
 * @author5
 * @create 2018-06-02 下午1:24
 *
 *
 * 读写锁的介绍
 **/
public class ReentrantLockDemo {


    private static Lock readLockock = new ReentrantReadWriteLock().readLock();

    private static Lock writeLock = new ReentrantReadWriteLock().writeLock();


    public static void main(String[] args) {

    }

}
package com.fh.interview;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author
 * @create 2018-06-02 下午3:30
 **/
public class AwaitSignal {

    private static ReentrantLock lock = new ReentrantLock();

    private static Condition condition = lock.newCondition();

    private static boolean flag = false;

    public static void main(String[] args) {
        Thread thread = new Thread(new Waiter());
        thread.start();
        try {
            Thread.sleep(3000);
        }catch (Exception e){

        }

        Thread thread1 = new Thread(new Signaler());
        thread1.start();
    }


    static class Waiter implements Runnable{
        @Override
        public void run() {
            lock.lock();
            try {
                while (!flag){
                    System.out.println("条件不满足");
                    condition.await();
                }
                System.out.println("条件满足");
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }

    static class Signaler implements Runnable{
        @Override
        public void run() {
            lock.lock();
            try {
                flag=true;
                condition.signalAll();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }
}

 

以上是关于读写锁,await和signa的主要内容,如果未能解决你的问题,请参考以下文章

读写锁 与 互斥锁

visA异步锁怎么使用

java中ReentrantReadWriteLock读写锁的使用

Swift新async/await并发中利用Task防止指定代码片段执行的数据竞争(Data Race)问题

Swift新async/await并发中利用Task防止指定代码片段执行的数据竞争(Data Race)问题

ReentrantReadWriteLock场景应用