ReentrantLock重入锁的使用示例

package com.itlaoqi.testdeploy.controller.test.aqs;

import java.util.concurrent.locks.ReentrantLock;

public class UseReenTrantLock {
    private ReentrantLock reentrantLock=new ReentrantLock();

    private  void method(){
        reentrantLock.lock();
        try {
            System.err.println("当前线程"+Thread.currentThread().getName()+"进入。。。");
            Thread.sleep(2000);
            System.err.println("当前线程"+Thread.currentThread().getName()+"退出。。。");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            reentrantLock.unlock();
        }
    }
    public static void main(String[] args){
        UseReenTrantLock useReenTrantLock=new UseReenTrantLock();
        Thread t1=new Thread(new Runnable() {
            @Override
            public void run() {
                useReenTrantLock.method();
            }
        },"t1");

        Thread t2=new Thread(new Runnable() {
            @Override
            public void run() {
                useReenTrantLock.method();
            }
        },"t2");
        t1.start();
        t2.start();

    }
}

你可能感兴趣的:(javaee)