Skip to content

Instantly share code, notes, and snippets.

@visparashar
Created June 22, 2018 04:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save visparashar/4254e1bf27cb5f608e7ff2c9125e2dfb to your computer and use it in GitHub Desktop.
Save visparashar/4254e1bf27cb5f608e7ff2c9125e2dfb to your computer and use it in GitHub Desktop.
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment