B9 Concurrent reentrant lock (of ReentrantLock)

[ Overview ]

  

[ Code examples ]

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

Print Results:

[ Lock () method of processing flow ]

  

Guess you like

Origin www.cnblogs.com/zlxyt/p/11105052.html
Recommended