modor
10/30/2017 - 5:58 AM

ReentrantLockTest

package servlet.test;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		CustomThreadReentrantLock customThreadReentrantLock = new CustomThreadReentrantLock();
		new Thread(customThreadReentrantLock).start();
		new Thread(customThreadReentrantLock).start();
		new Thread(customThreadReentrantLock).start();
	}

}

class CustomThreadReentrantLock implements Runnable {
	private int i = 0;
	ReentrantLock reentrantLock = new ReentrantLock();

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (true) {
			reentrantLock.lock();
			try {
				i++;
				Thread.sleep(1000);
				System.out.println(i);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				reentrantLock.unlock();
			}
		}
	}
}