File tree Expand file tree Collapse file tree 2 files changed +75
-0
lines changed 
src/com/winterbe/java8/samples/concurrent Expand file tree Collapse file tree 2 files changed +75
-0
lines changed Original file line number Diff line number Diff line change 1+ package  com .winterbe .java8 .samples .concurrent ;
2+ 
3+ import  java .util .concurrent .ExecutorService ;
4+ import  java .util .concurrent .Executors ;
5+ import  java .util .concurrent .locks .ReentrantLock ;
6+ import  java .util .stream .IntStream ;
7+ 
8+ /** 
9+  * @author Benjamin Winterberg 
10+  */ 
11+ public  class  Lock1  {
12+ 
13+  private  static  final  int  NUM_INCREMENTS  = 10000 ;
14+ 
15+  private  static  ReentrantLock  lock  = new  ReentrantLock ();
16+ 
17+  private  static  int  count  = 0 ;
18+ 
19+  private  static  void  increment () {
20+  lock .lock ();
21+  try  {
22+  count ++;
23+  }
24+  finally  {
25+  lock .unlock ();
26+  }
27+  }
28+ 
29+  public  static  void  main (String [] args ) {
30+  testLock ();
31+  }
32+ 
33+  private  static  void  testLock () {
34+  count  = 0 ;
35+ 
36+  ExecutorService  executor  = Executors .newFixedThreadPool (2 );
37+ 
38+  IntStream .range (0 , NUM_INCREMENTS )
39+  .forEach (i  -> executor .submit (Lock1 ::increment ));
40+ 
41+  ConcurrentUtils .stop (executor );
42+ 
43+  System .out .println (count );
44+  }
45+ 
46+ }
Original file line number Diff line number Diff line change 1+ package  com .winterbe .java8 .samples .concurrent ;
2+ 
3+ import  java .util .concurrent .ExecutorService ;
4+ import  java .util .concurrent .Executors ;
5+ import  java .util .concurrent .locks .ReentrantLock ;
6+ 
7+ /** 
8+  * @author Benjamin Winterberg 
9+  */ 
10+ public  class  Lock2  {
11+ 
12+  public  static  void  main (String [] args ) {
13+  ExecutorService  executor  = Executors .newFixedThreadPool (2 );
14+ 
15+  ReentrantLock  lock  = new  ReentrantLock ();
16+ 
17+  executor .submit (() -> {
18+  lock .lock ();
19+  try  {
20+  System .out .println (lock .isLocked ());
21+  } finally  {
22+  lock .unlock ();
23+  }
24+  });
25+ 
26+  ConcurrentUtils .stop (executor );
27+  }
28+ 
29+ }
                                 You can’t perform that action at this time. 
               
                  
0 commit comments