多线程系列三:Lock和Condition

有了synchronized为什么还要Lock?

因为Lock和synchronized比较有如下优点

1、 尝试非阻塞地获取锁

2、 获取锁的过程可以被中断

3、 超时获取锁

Lock的标准用法

 1 package com.lgs;
 2 
 3 import java.util.concurrent.locks.Lock;
 4 import java.util.concurrent.locks.ReentrantLock;
 5 
 6 /**
 7  * lgs
 8  * 显示锁lock的标准写法
 9  */
10 public class LockTemplete {
11 
12     public static void main(String[] args) {
13         Lock lock = new ReentrantLock();
14         //获取锁
15         lock.lock();
16         try{
17             // do my work.....
18         }finally{
19             //释放锁
20             lock.unlock();
21         }
22     }
23 
24 }

Lock的常用方法

Lock() 获取锁

tryLock尝试非阻塞地获取锁

lockInterruptibly:获取锁的过程可以被中断

tryLock(long time, TimeUnit unit) 超时获取锁

unlock()释放锁

锁的可重入

一个线程获得了锁进入了同步代码块遇到了锁仍然可以进入同步代码块

递归的时候发生锁的重入,没有锁的可重入,就会死锁

公平和非公平锁

公平锁,先对锁发出获取请求的一定先被满足。公平锁的效率比非公平锁效率要低。

为什么非公平锁的性能要高:因为非公平锁是可以插队的,如线程C被唤醒变为可执行去获取锁的过程中,线程A插队进来直接获取锁执行自己的业务,线程A执行完以后,线程C刚好唤醒完直接就获取锁运行了,这样在线程C唤醒的过程中线程A就执行完了效率更高

读写锁ReentrantReadWriteLock

允许多个读线程同时进行,但是只允许一个写线程(不允许其他读线程防止脏读和写线程),支持读多写少场景,性能会有提升。

 1 package com.lgs;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 import java.util.concurrent.locks.Lock;
 6 import java.util.concurrent.locks.ReentrantLock;
 7 import java.util.concurrent.locks.ReentrantReadWriteLock;
 8 
 9 /**
10  * lgs
11  * 读写锁的使用
12  */
13 public class RwLockTemplete {
14 
15     static final Map<String,String> map = new HashMap<>();
16     static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
17     static Lock r = reentrantReadWriteLock.readLock();
18     static Lock w = reentrantReadWriteLock.writeLock();
19 
20     public void put(){
21         w.lock();
22         try{
23             // do my work.....
24         }finally{
25             w.unlock();
26         }
27     }
28 
29     public void get(){
30         r.lock();
31         try{
32             // do my work.....
33         }finally{
34             r.unlock();
35         }
36     }
37 
38 }

Condition接口有何用处?

Object的 wait,notify/notifyAll 实现等待通知机制

 Condition接口和Lock配合来实现等待通知机制

Condition常用方法和使用范式

 1 package com.lgs;
 2 
 3 import java.util.concurrent.locks.Condition;
 4 import java.util.concurrent.locks.Lock;
 5 import java.util.concurrent.locks.ReentrantLock;
 6 
 7 /**
 8  * lgs
 9  * Condition的使用方式
10  */
11 public class ConditionTemplete {
12 
13     Lock lock = new ReentrantLock();
14     Condition condition = lock.newCondition();
15 
16     public void waitc() throws InterruptedException {
17         lock.lock();
18         try{
19             condition.await();
20         }finally{
21             lock.unlock();
22         }
23     }
24 
25     public void waitnotify() throws InterruptedException {
26         lock.lock();
27         try{
28             condition.signal();
29             //condition.signalAll();尽量少使用
30         }finally{
31             lock.unlock();
32         }
33     }
34 
35 
36 }

结合ReentrantLock和Condition实现线程安全的有界队列

 1 package com.lgs.bq;
 2 
 3 import java.util.LinkedList;
 4 import java.util.List;
 5 import java.util.concurrent.locks.Condition;
 6 import java.util.concurrent.locks.Lock;
 7 import java.util.concurrent.locks.ReentrantLock;
 8 
 9 /**
10  * lgs
11  * 结合ReentrantLock和Condition实现线程安全的有界队列
12  */
13 public class BlockingQueueLC<T> {
14     private List queue = new LinkedList<>();
15     private final int limit;
16     Lock lock = new ReentrantLock();
17     private Condition needNotEmpty = lock.newCondition();
18     private Condition needNotFull = lock.newCondition();
19 
20 
21     public BlockingQueueLC(int limit) {
22         this.limit = limit;
23     }
24 
25     public void enqueue(T item) throws InterruptedException {
26         lock.lock();
27         try{
28             while(this.queue.size()==this.limit){
29                 needNotFull.await();
30             }
31             this.queue.add(item);
32             //通知出队线程有数据可以取了
33             needNotEmpty.signal();
34         }finally{
35             lock.unlock();
36         }
37     }
38 
39     public  T dequeue() throws InterruptedException {
40         lock.lock();
41         try{
42             while(this.queue.size()==0){
43                 needNotEmpty.await();
44             }
45             //通知入队线程有位置可以入队了
46             needNotFull.signal();
47             return (T) this.queue.remove(0);
48         }finally{
49             lock.unlock();
50         }
51     }
52 }
package com.lgs.bq;

/**
 * 
 */
public class BqTest {
    public static void main(String[] args) {
        BlockingQueueLC<Integer> bq = new BlockingQueueLC(10);
        Thread threadA = new ThreadPush(bq);
        threadA.setName("Push");
        Thread threadB = new ThreadPop(bq);
        threadB.setName("Pop");
        threadB.start();
        threadA.start();
    }

    private static class ThreadPush extends Thread{
        BlockingQueueLC<Integer> bq;

        public ThreadPush(BlockingQueueLC<Integer> bq) {
            this.bq = bq;
        }

        @Override
        public void run() {
            String threadName = Thread.currentThread().getName();
            int i = 5;
            while(i>0){
                try {
                    Thread.sleep(500);
                    System.out.println(" i="+i+" will push");
                    bq.enqueue(i--);
                } catch (InterruptedException e) {
                    //e.printStackTrace();
                }

            }
        }
    }

    private static class ThreadPop extends Thread{
        BlockingQueueLC<Integer> bq;

        public ThreadPop(BlockingQueueLC<Integer> bq) {
            this.bq = bq;
        }
        @Override
        public void run() {
            while(true){
                try {
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName()+" will pop.....");
                    Integer i = bq.dequeue();
                    System.out.println(" i="+i.intValue()+" alread pop");
                } catch (InterruptedException e) {
                    //e.printStackTrace();
                }
            }

        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_26676207/article/details/81110814