Guest User

Untitled

a guest
Jun 23rd, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. package com.learning;
  2.  
  3. import java.util.concurrent.locks.Lock;
  4. import java.util.concurrent.locks.ReentrantLock;
  5.  
  6. public class ReentranceLockDemo {
  7.  
  8. final static Custom c= new Custom();
  9.  
  10. public static void main(String[] args) throws InterruptedException {
  11. MyRunner runner =new MyRunner(c);
  12. Thread th = new Thread(runner);
  13. MyRunner1 runner1 =new MyRunner1(c);
  14. Thread th1 = new Thread(runner1);
  15.  
  16. th.start();
  17. th1.start();
  18. th.join();
  19. th1.join();
  20. c.finished();
  21. }
  22. }
  23. class MyRunner implements Runnable {
  24.  
  25. final Custom c ;
  26.  
  27. MyRunner(Custom c){
  28. this.c=c;
  29. }
  30.  
  31. @Override
  32. public void run() {
  33.  
  34. c.incrementForThread1();
  35.  
  36. }
  37.  
  38. }
  39.  
  40. class MyRunner1 implements Runnable {
  41.  
  42. final Custom c ;
  43.  
  44. MyRunner1(Custom c){
  45. this.c=c;
  46. }
  47.  
  48. @Override
  49. public void run() {
  50. c.incrementForThread2();
  51. }
  52.  
  53. }
  54.  
  55. class Custom {
  56.  
  57. int count =0;
  58.  
  59. Lock lock = new ReentrantLock();
  60.  
  61. public void incrementForThread1() {
  62. for(int i =0;i<10000;i++) {
  63. lock.lock();
  64. count++;
  65. lock.unlock();
  66. }
  67. }
  68.  
  69. public void incrementForThread2() {
  70. for(int i =0;i<10000;i++) {
  71. lock.lock();
  72. count++;
  73. lock.unlock();
  74. }
  75. }
  76.  
  77. public void finished() {
  78. System.out.println("Count is "+count);
  79. }
  80.  
  81.  
  82. }
Add Comment
Please, Sign In to add comment