Created
June 22, 2018 04:36
-
-
Save visparashar/4254e1bf27cb5f608e7ff2c9125e2dfb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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