JDK1.8-ReentrantLock解锁过程

ReentrantLock解锁流程图

JDK1.8-ReentrantLock解锁过程_第1张图片

  1. 实例代码
package com.sap.leo.test;

import com.sun.xml.internal.bind.v2.model.annotation.RuntimeAnnotationReader;
import jdk.nashorn.internal.ir.Block;

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

public class LeoTest
{
    final static Lock lock = new ReentrantLock(true);
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                //t1加锁
                lock.lock();
                System.out.println(Thread.currentThread().getName()+" 睡眠5s");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }

            }
        },"t1");
        t1.start();

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {

                System.out.println("t2 加锁...");
                //t2加锁,如果t1没有释放锁,那么t2会被加入阻塞队列
                lock.lock();
                System.out.println("t1 解锁成功");
                System.out.println("t2 加锁成功");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        },"t1");
        t2.start();

    }
}

2.输出结果

JDK1.8-ReentrantLock解锁过程_第2张图片

 注意:

  • ReentrantLock.lock():手动加锁需要手动释放锁。

你可能感兴趣的:(并发,Java)