Java并发系列:ReentrantLock 重入锁的使用

/ JavaSE / 533浏览

ReentrantLock 是jdk1.5之后,并发包中新增了Lock接口(以及相关实现类)用来实现锁的功能,它提供了与synchronized关键字类似的同步功能。
相比synchronized,多了以下功能:

相比synchronized 之间的差异:

package cn.zealon.lock;

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

/**
 * 重入锁用例
 */
public class UseReentrantLock implements Runnable {

    private Lock lock = new ReentrantLock();

    public void func(){
        lock.lock();
        System.out.println("
"+Thread.currentThread().getName());

        try{
            for(int i=0;i<10;i++){
                System.out.print(" "+i);
            }
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void run() {
        func();
    }

    public static void main(String[] args){
        UseReentrantLock useReentrantLock = new UseReentrantLock();
        //UseReentrantLock useReentrantLock2 = new UseReentrantLock();
        Thread t1 = new Thread(useReentrantLock);
        Thread t2 = new Thread(useReentrantLock);

        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(t1);
        executorService.execute(t2);
        executorService.shutdown();
    }
}

输出结果(保证了线程1执行完,再执行线程2):

pool-1-thread-1
 0 1 2 3 4 5 6 7 8 9
pool-1-thread-2
 0 1 2 3 4 5 6 7 8 9

不加锁的输出结果(每次不一样):

pool-1-thread-1

pool-1-thread-2
 0 1 2 3 4 5 0 6 1 7 2 3 4 5 8 6 9 7 8 9