廖雪峰Java11多线程编程-3高级concurrent包-1ReentrantLock

Posted csj2018

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了廖雪峰Java11多线程编程-3高级concurrent包-1ReentrantLock相关的知识,希望对你有一定的参考价值。

线程同步:

  • 是因为多线程读写竞争资源需要同步
  • Java语言提供了synchronized/wait/notify
  • 编写多线程同步很困难

所以Java提供了java.util.concurrent包:

  • 更高级的同步功能
  • 简化多线程程序的编写
  • JDK>= 1.5

java.util.locks.ReetrantLock用于替代synchronized加锁
```#java
synchronized(lockObj)
n = n + 1;

final Lock lock = new ReetrantLock()
lock.lock()
try
n = n + 1;
finally
lock.unlock();

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

class Counter
    private Lock lock = new ReentrantLock();
    private int value = 0;
    public void add(int m)
        lock.lock();
        try
            value += m;
        finally 
            lock.unlock();
        
    
    public void dec(int m)
        lock.lock();
        try
            value -= m;
        finally 
            lock.unlock();
        
    
    public int get()
        lock.lock();
        try
            return this.value;
        finally 
            lock.unlock();
        
    

public class Main
    final static int LOOP = 100;
    public static void main(String[] args) throws Exception
        Counter counter = new Counter();
        Thread t1 = new Thread()
            public void run()
                for(int i=0;i<LOOP;i++)
                    counter.add(1);
                
            
        ;
        Thread t2 = new Thread()
            public void run()
                for(int i=0;i<LOOP;i++)
                    counter.dec(1);
                
            
        ;
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(counter.get());
    

tryLock()可指定超时
总结:
ReentrantLock可以替代synchronized
ReentrantLock获取锁更安全
获取锁在try...finally之前
必须使用try... finallu保证正确释放锁

以上是关于廖雪峰Java11多线程编程-3高级concurrent包-1ReentrantLock的主要内容,如果未能解决你的问题,请参考以下文章

廖雪峰Java11多线程编程-4线程工具类-1ThreadLocal

廖雪峰Java11多线程编程-2线程同步-2synchronized方法

廖雪峰Java13网络编程-1Socket编程-3TCP多线程编程

20200225 Java 多线程-廖雪峰

20200225 Java 多线程-廖雪峰

廖雪峰Java13网络编程-3其他-1HTTP编程