B9 Concurrent 重入锁(ReentrantLock)

概述

  

代码实例

import java.util.concurrent.locks.ReentrantLock;

public class Main {

	public static void main(String[] args) {
		Command c = new Command();
		int nThreads = 5;
		for(int i = 0; i < nThreads; i++){
			new Thread(c).start();
		}
	}

}

class Command implements Runnable {
	
	ReentrantLock lock = new ReentrantLock();
	
	@Override
	public void run() {
		try{
			lock.lock();
			System.out.println(Thread.currentThread().getName() + ": 获得锁!");
		}catch(Exception e){
			//处理异常
		}finally{
			System.out.println(Thread.currentThread().getName() + ": 释放锁!");
			lock.unlock();
		}
	}
}

打印结果:

lock() 方法处理流程

  

猜你喜欢

转载自www.cnblogs.com/zlxyt/p/11105052.html
今日推荐