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

读写锁,await和signa

时间:2018-06-02 16:35:46      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:dwr   package   finally   时间   star   读写锁   try   sleep   over   

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

标签:dwr   package   finally   时间   star   读写锁   try   sleep   over   

原文地址:https://www.cnblogs.com/nihaofenghao/p/9125592.html

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