好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java中的显示锁ReentrantLock使用与原理详解

考虑一个场景,轮流打印0-100以内的技术和偶数。通过使用 synchronize 的 wait,notify机制就可以实现,核心思路如下:
使用两个线程,一个打印奇数,一个打印偶数。这两个线程会共享一个数据,数据每次自增,当打印奇数的线程发现当前要打印的数字不是奇数时,执行等待,否则打印奇数,并将数字自增1,对于打印偶数的线程也是如此

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

//打印奇数的线程

private static class oldrunner implements runnable{

   private mynumber n;

 

   public oldrunner(mynumber n) {

     this .n = n;

   }

 

   public void run() {

     while ( true ){

       n.waittoold(); //等待数据变成奇数

       system.out.println( "old:" + n.getval());

       n.increase();

       if (n.getval()> 98 ){

         break ;

       }

     }

   }

}

//打印偶数的线程

private static class evenrunner implements runnable{

   private mynumber n;

 

   public evenrunner(mynumber n) {

     this .n = n;

   }

 

   public void run() {

     while ( true ){

       n.waittoeven();      //等待数据变成偶数

       system.out.println( "even:" +n.getval());

       n.increase();

       if (n.getval()> 99 ){

         break ;

       }

     }

   }

}

共享的数据如下

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

private static class mynumber{

   private int val;

 

   public mynumber( int val) {

     this .val = val;

   }

 

   public int getval() {

     return val;

   }

   public synchronized void increase(){

     val++;

     notify(); //数据变了,唤醒另外的线程

   }

   public synchronized void waittoold(){

     while ((val % 2 )== 0 ){

       try {

         system.out.println( "i am " +thread.currentthread().getname()+ " ,but now is even:" +val+ ",so wait" );

         wait(); //只要是偶数,一直等待

       } catch (interruptedexception e) {

         e.printstacktrace();

       }

     }

   }

   public synchronized void waittoeven(){

     while ((val % 2 )!= 0 ){

       try {

         system.out.println( "i am " +thread.currentthread().getname()+ " ,but now old:" +val+ ",so wait" );

         wait(); //只要是奇数,一直等待

       } catch (interruptedexception e) {

         e.printstacktrace();

       }

     }

   }

}

运行代码如下

?

1

2

3

4

5

mynumber n = new mynumber( 0 );

thread old= new thread( new oldrunner(n), "old-thread" );

thread even = new thread( new evenrunner(n), "even-thread" );

old.start();

even.start();

运行结果如下

i am old-thread ,but now is even:0,so wait
even:0
i am even-thread ,but now old:1,so wait
old:1
i am old-thread ,but now is even:2,so wait
even:2
i am even-thread ,but now old:3,so wait
old:3
i am old-thread ,but now is even:4,so wait
even:4
i am even-thread ,but now old:5,so wait
old:5
i am old-thread ,but now is even:6,so wait
even:6
i am even-thread ,but now old:7,so wait
old:7
i am old-thread ,but now is even:8,so wait
even:8

上述方法使用的是 synchronize的 wait notify机制,同样可以使用显示锁来实现,两个打印的线程还是同一个线程,只是使用的是显示锁来控制等待事件

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

private static class mynumber{

   private lock lock = new reentrantlock();

   private condition condition = lock.newcondition();

   private int val;

 

   public mynumber( int val) {

     this .val = val;

   }

 

   public int getval() {

     return val;

   }

   public void increase(){

     lock.lock();

     try {

       val++;

       condition.signalall(); //通知线程

     } finally {

       lock.unlock();

     }

 

   }

   public void waittoold(){

     lock.lock();

     try {

       while ((val % 2 )== 0 ){

         try {

           system.out.println( "i am should print old ,but now is even:" +val+ ",so wait" );

           condition.await();

         } catch (interruptedexception e) {

           e.printstacktrace();

         }

       }

     } finally {

       lock.unlock();

     }

   }

   public void waittoeven(){

     lock.lock(); //显示的锁定

     try {

       while ((val % 2 )!= 0 ){

         try {

           system.out.println( "i am should print even ,but now old:" +val+ ",so wait" );

           condition.await(); //执行等待

         } catch (interruptedexception e) {

           e.printstacktrace();

         }

       }

     } finally {

       lock.unlock(); //显示的释放

     }

 

   }

}

同样可以得到上述的效果

显示锁的功能

显示锁在java中通过接口lock提供如下功能

lock: 线程无法获取锁会进入休眠状态,直到获取成功

lockinterruptibly: 如果获取成功,立即返回,否则一直休眠到线程被中断或者是获取成功 trylock:不会造成线程休眠,方法执行会立即返回,获取到了锁,返回true,否则返回false trylock(long time, timeunit unit) throws interruptedexception : 在等待时间内没有发生过中断,并且没有获取锁,就一直等待,当获取到了,或者是线程中断了,或者是超时时间到了这三者发生一个就返回,并记录是否有获取到锁 unlock:释放锁 newcondition:每次调用创建一个锁的等待条件,也就是说一个锁可以拥有多个条件

condition的功能

接口condition把object的监视器方法wait和notify分离出来,使得一个对象可以有多个等待的条件来执行等待,配合lock的newcondition来实现。

await:使当前线程休眠,不可调度。这四种情况下会恢复 1:其它线程调用了signal,当前线程恰好被选中了恢复执行;2: 其它线程调用了signalall;3:其它线程中断了当前线程 4:spurious wakeup (假醒)。无论什么情况,在await方法返回之前,当前线程必须重新获取锁 awaituninterruptibly:使当前线程休眠,不可调度。这三种情况下会恢复 1:其它线程调用了signal,当前线程恰好被选中了恢复执行;2: 其它线程调用了signalall;3:spurious wakeup (假醒)。 awaitnanos:使当前线程休眠,不可调度。这四种情况下会恢复 1:其它线程调用了signal,当前线程恰好被选中了恢复执行;2: 其它线程调用了signalall;3:其它线程中断了当前线程 4:spurious wakeup (假醒)。5:超时了 await(long time, timeunit unit) :与awaitnanos类似,只是换了个时间单位 awaituntil(date deadline):与awaitnanos相似,只是指定日期之后返回,而不是指定的一段时间 signal:唤醒一个等待的线程 signalall:唤醒所有等待的线程

reentrantlock

从源码中可以看到,reentrantlock的所有实现全都依赖于内部类sync和conditionobject。

sync本身是个抽象类,负责手动lock和unlock,conditionobject则实现在父类abstractownablesynchronizer中,负责await与signal

sync的继承结构如下

sync的两个实现类,公平锁和非公平锁

公平的锁会把权限给等待时间最长的线程来执行,非公平则获取执行权限的线程与线程本身的等待时间无关

默认初始化reentrantlock使用的是非公平锁,当然可以通过指定参数来使用公平锁

?

1

2

3

public reentrantlock() {

   sync = new nonfairsync();

}

当执行获取锁时,实际就是去执行 sync 的lock操作:

?

1

2

3

public void lock() {

   sync.lock();

}

对应在不同的锁机制中有不同的实现

1、公平锁实现

?

1

2

3

final void lock() {

   acquire( 1 );

}

2、非公平锁实现

?

1

2

3

4

5

6

final void lock() {

   if (compareandsetstate( 0 , 1 )) //先看当前锁是不是已经被占有了,如果没有,就直接将当前线程设置为占有的线程

     setexclusiveownerthread(thread.currentthread());

   else    

     acquire( 1 ); //锁已经被占有的情况下,尝试获取

}

二者都调用父类abstractqueuedsynchronizer的方法

?

1

2

3

4

5

public final void acquire( int arg) {

   if (!tryacquire(arg) &&

     acquirequeued(addwaiter(node.exclusive), arg)) //一旦抢失败,就会进入队列,进入队列后则是依据fifo的原则来执行唤醒

     selfinterrupt();

}

当执行unlock时,对应方法在父类abstractqueuedsynchronizer中

?

1

2

3

4

5

6

7

8

9

public final boolean release( int arg) {

   if (tryrelease(arg)) {

     node h = head;

     if (h != null && h.waitstatus != 0 )

       unparksuccessor(h);

     return true ;

   }

   return false ;

}

公平锁和非公平锁则分别对获取锁的方式 tryacquire 做了实现,而tryrelease的实现机制则都是一样的

公平锁实现tryacquire

源码如下

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

protected final boolean tryacquire( int acquires) {

   final thread current = thread.currentthread();

   int c = getstate(); //获取当前的同步状态

   if (c == 0 ) {

     //等于0 表示没有被其它线程获取过锁

     if (!hasqueuedpredecessors() &&

       compareandsetstate( 0 , acquires)) {

       //hasqueuedpredecessors 判断在当前线程的前面是不是还有其它的线程,如果有,也就是锁sync上有一个等待的线程,那么它不能获取锁,这意味着,只有等待时间最长的线程能够获取锁,这就是是公平性的体现

       //compareandsetstate 看当前在内存中存储的值是不是真的是0,如果是0就设置成accquires的取值。对于java,这种需要直接操作内存的操作是通过unsafe来完成,具体的实现机制则依赖于操作系统。

       //存储获取当前锁的线程

       setexclusiveownerthread(current);

       return true ;

     }

   }

   else if (current == getexclusiveownerthread()) {

     //判断是不是当前线程获取的锁

     int nextc = c + acquires;

     if (nextc < 0 ) //一个线程能够获取同一个锁的次数是有限制的,就是int的最大值

       throw new error( "maximum lock count exceeded" );

     setstate(nextc); //在当前的基础上再增加一次锁被持有的次数

     return true ;

   }

   //锁被其它线程持有,获取失败

   return false ;

}

非公平锁实现tryacquire

获取的关键实现为 nonfairtryacquire ,源码如下

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

final boolean nonfairtryacquire( int acquires) {

   final thread current = thread.currentthread();

   int c = getstate();

   if (c == 0 ) {

     //锁没有被持有

     //可以看到这里会无视sync queue中是否有其它线程,只要执行到了当前线程,就会去获取锁

     if (compareandsetstate( 0 , acquires)) {

       setexclusiveownerthread(current); //在判断一次是不是锁没有被占有,没有就去标记当前线程拥有这个锁了

       return true ;

     }

   }

   else if (current == getexclusiveownerthread()) {

     int nextc = c + acquires;

     if (nextc < 0 ) // overflow     

       throw new error( "maximum lock count exceeded" );

     setstate(nextc); //如果当前线程已经占有过,增加占有的次数

     return true ;

   }

   return false ;

}

释放锁的机制

?

1

2

3

4

5

6

7

8

9

10

11

12

13

protected final boolean tryrelease( int releases) {

   int c = getstate() - releases;

   if (thread.currentthread() != getexclusiveownerthread()) //只能是线程拥有这释放

     throw new illegalmonitorstateexception();

   boolean free = false ;

   if (c == 0 ) {

     //当占有次数为0的时候,就认为所有的锁都释放完毕了

     free = true ;

     setexclusiveownerthread( null );

   }

   setstate(c); //更新锁的状态

   return free;

}

从源码的实现可以看到

reentrantlock获取锁时,在锁已经被占有的情况下,如果占有锁的线程是当前线程,那么允许重入,即再次占有,如果由其它线程占有,则获取失败,由此可见, reetrantlock本身对锁的持有是可重入的,同时是线程独占的 。

公平与非公平就体现在,当执行的线程去获取锁的时候,公平的会去看是否有等待时间比它更长的,而非公平的就优先直接去占有锁

reentrantlock的trylock()与trylock(long timeout, timeunit unit):

?

1

2

3

4

public boolean trylock() {

//本质上就是执行一次非公平的抢锁

return sync.nonfairtryacquire( 1 );

}

有时限的trylock核心代码是 sync.tryacquirenanos(1, unit.tonanos(timeout)); ,由于有超时时间,它会直接放到等待队列中,他与后面要讲的aqs的lock原理中acquirequeued的区别在于park的时间是有限的,详见源码 abstractqueuedsynchronizer.doacquirenanos

为什么需要显示锁

内置锁功能上有一定的局限性,它无法响应中断,不能设置等待的时间

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:https://segmentfault.com/a/1190000017134892

查看更多关于Java中的显示锁ReentrantLock使用与原理详解的详细内容...

  阅读:8次