十四、ReentrantLock重入锁

一、简介

JDK提供了Lock接口来实现更丰富的锁控制,ReentrantLock即Lock接口的实现

JDK文档:http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/concurrent/locks/ReentrantLock.html

二、代码示例

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockDemo {
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            lock.lock();
            System.out.println(Thread.currentThread().getName());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.unlock();
        }).start();
        Thread.sleep(10);
        lock.lock();
        System.out.println("main");
        lock.unlock();
    }

}

猜你喜欢

转载自www.cnblogs.com/lay2017/p/10166501.html