1. 程式人生 > >十四、ReentrantLock重入鎖

十四、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(); } }