锁(ReentrantLock、ReentrantReadWri

2018-10-28  本文已影响0人  笑才

参考:https://www.cnblogs.com/dolphin0520/p/3923167.html

1、ReentrantLock(实现Lock接口)

public class LockTest01 {
    private Lock lock = new ReentrantLock();
    private ArrayList<Integer> arrayList = new ArrayList<Integer>();
    public static void main(String[] args) {
        final LockTest01 test = new LockTest01();
        new Thread(){
            public void run(){
                test.insert(Thread.currentThread());
            }
        }.start();
        new Thread(){
            public void run(){
                test.insert(Thread.currentThread());
            }
        }.start();
    }
    
    public void insert(Thread thread){
        lock.lock();//获得锁,如果获取不到则线程等待
        //lock.lockInterruptibly();可中断的获取锁,获取不到时可以中断线程(注意:线程获取到锁后是不能被中断的)
        //lock.tryLock();尝试获取锁,返回boolean值,获取到返回true否则返回false,线程不等待
        try {
            System.out.println(thread.getName()+"得到了锁");
            for(int i=0;i<5;i++){arrayList.add(i);}
        } catch (Exception e) {
            
        } finally{
            System.out.println(thread.getName()+"释放了锁");
            lock.unlock();//解锁
        }
    };
}

2、ReentrantReadWriteLock读写锁 (实现了ReadWriteLock接口)

ReentrantLock lock = new ReentrantLock(true);设置锁的公平性
ReentrantReadWriteLock里面提供了很多丰富的方法,不过最主要的有两个方法:readLock()和writeLock()用来获取读锁和写锁。

public class LockTest02 {
    private ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock();
    public static void main(String[] args) {
        final LockTest02 test = new LockTest02();
        new Thread(){
            public void run(){
                test.get(Thread.currentThread());
            }
        }.start();
        new Thread(){
            public void run(){
                test.get(Thread.currentThread());
            }
        }.start();
    }
    
    public void get(Thread thread){
        rwlock.readLock().lock();
        try {
            long startTime = System.currentTimeMillis();
            while(System.currentTimeMillis()-startTime<1){
                System.out.println(thread.getName()+"正在进行读操作");
            }
            System.out.println(thread.getName()+"读操作完毕");
        } catch (Exception e) {
        } finally{
            rwlock.readLock().unlock();
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读