Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.learning;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class ReentranceLockDemo {
- final static Custom c= new Custom();
- public static void main(String[] args) throws InterruptedException {
- MyRunner runner =new MyRunner(c);
- Thread th = new Thread(runner);
- MyRunner1 runner1 =new MyRunner1(c);
- Thread th1 = new Thread(runner1);
- th.start();
- th1.start();
- th.join();
- th1.join();
- c.finished();
- }
- }
- class MyRunner implements Runnable {
- final Custom c ;
- MyRunner(Custom c){
- this.c=c;
- }
- @Override
- public void run() {
- c.incrementForThread1();
- }
- }
- class MyRunner1 implements Runnable {
- final Custom c ;
- MyRunner1(Custom c){
- this.c=c;
- }
- @Override
- public void run() {
- c.incrementForThread2();
- }
- }
- class Custom {
- int count =0;
- Lock lock = new ReentrantLock();
- public void incrementForThread1() {
- for(int i =0;i<10000;i++) {
- lock.lock();
- count++;
- lock.unlock();
- }
- }
- public void incrementForThread2() {
- for(int i =0;i<10000;i++) {
- lock.lock();
- count++;
- lock.unlock();
- }
- }
- public void finished() {
- System.out.println("Count is "+count);
- }
- }
Add Comment
Please, Sign In to add comment