好得很程序员自学网

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

java ReentrantLock详解

介绍

reentrantlock称为重入锁,比内部锁synchonized拥有更强大的功能,它可中断、可定时、设置公平锁

【注】使用reentrantlock时,一定要释放锁,一般释放放到finnal里写。

提供以下重要的方法

lock():获得锁,如果锁已被占用,则等待 lockinterruptibly():获得锁,但有限响应中断 unlock():释放锁 trylock():尝试获取锁。如果获得,返回true;否则返回false trylock(long time, timeunit unit):在给定时间内获得锁。如果获得返回true;否则返回false

示例

例子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

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

import java.util.concurrent.locks.reentrantlock;

 

public class reentrantlocktest {

  reentrantlock lock;

 

  reentrantlocktest(reentrantlock lock) {

   this .lock = lock;

  }

 

  private runnable getrunnable() {

   return new runnable() {

    @override

    public void run() {

     while ( true ) {

      try {

       if (lock.trylock()) {

        try {

         system.out.println( "locked:" + thread.currentthread().getname());

         thread.sleep( 800 );

        } finally {

         lock.unlock();

         system.out.println( "unlocked:" + thread.currentthread().getname());

        }

        system.out.println( "break before" );

        break ;

       } else {

        //system.out.println("unable to lock " + thread.currentthread().getname());

       }

 

      } catch (interruptedexception e){

       system.out.println(thread.currentthread() + " is interupted" );

       e.printstacktrace();

      }

     }

    }

   };

  }

 

  public static void main(string[] args) {

   reentrantlock lock = new reentrantlock();

   reentrantlocktest test = new reentrantlocktest(lock);

   reentrantlocktest test2 = new reentrantlocktest(lock);

   thread thread1 = new thread(test.getrunnable(), "firstthread" );

   thread thread2 = new thread(test2.getrunnable(), "secondthread" );

 

   thread1.start();

   thread2.start();

   try {

    thread.sleep( 300 );

   } catch (interruptedexception e) {

    e.printstacktrace();

   }

   system.out.println( "interupt begin" );

   thread2.interrupt();

   system.out.println( "interupt end" );

  }

}

一次执行结果:

locked:firstthread
interupt begin
interupt end
unlocked:firstthread
break before
locked:secondthread
unlocked:secondthread
thread[secondthread,5,main] is interupted
java.lang.interruptedexception: sleep interrupted
    at java.lang.thread.sleep(native method)
    at com.jihite.templet.javabase.reentrantlocktest$1.run(reentrantlocktest.java:23)
    at java.lang.thread.run(thread.java:748)
locked:secondthread
unlocked:secondthread
break before

 分析:firstthread执行,secondthread不停的判断是否可以获得锁,当firstthread执行完,secondthread执行后被打断

例子2

?

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

55

56

57

58

import java.util.concurrent.timeunit;

import java.util.concurrent.locks.reentrantlock;

 

public class reentrantlocktest {

  reentrantlock lock;

 

  reentrantlocktest(reentrantlock lock) {

   this .lock = lock;

  }

 

  private runnable getrunnable() {

   return new runnable() {

    @override

    public void run() {

     while ( true ) {

      try {

       if (lock.trylock( 700 , timeunit.milliseconds)) {

        try {

         system.out.println( "locked:" + thread.currentthread().getname());

         thread.sleep( 800 );

        } finally {

         lock.unlock();

         system.out.println( "unlocked:" + thread.currentthread().getname());

        }

        system.out.println( "break before" );

        break ;

       } else {

        //system.out.println("unable to lock " + thread.currentthread().getname());

       }

 

      } catch (interruptedexception e){

       system.out.println(thread.currentthread() + " is interupted" );

       e.printstacktrace();

      }

     }

    }

   };

  }

 

  public static void main(string[] args) {

   reentrantlock lock = new reentrantlock();

   reentrantlocktest test = new reentrantlocktest(lock);

   reentrantlocktest test2 = new reentrantlocktest(lock);

   thread thread1 = new thread(test.getrunnable(), "firstthread" );

   thread thread2 = new thread(test2.getrunnable(), "secondthread" );

 

   thread1.start();

   thread2.start();

   try {

    thread.sleep( 300 );

   } catch (interruptedexception e) {

    e.printstacktrace();

   }

   system.out.println( "interupt begin" );

   thread2.interrupt();

   system.out.println( "interupt end" );

  }

}

一次执行结果

locked:firstthread
interupt begin
interupt end
thread[secondthread,5,main] is interupted
java.lang.interruptedexception
    at java.util.concurrent.locks.abstractqueuedsynchronizer.doacquirenanos(abstractqueuedsynchronizer.java:936)
    at java.util.concurrent.locks.abstractqueuedsynchronizer.tryacquirenanos(abstractqueuedsynchronizer.java:1247)
    at java.util.concurrent.locks.reentrantlock.trylock(reentrantlock.java:442)
    at com.jihite.templet.javabase.reentrantlocktest$1.run(reentrantlocktest.java:19)
    at java.lang.thread.run(thread.java:748)
locked:secondthread
unlocked:firstthread
break before
unlocked:secondthread
break before

分析:firstthread执行,secondthread等待,等待过程被打断。打断后firstthread执行结束了,secondthread得到锁,继续执行

例子3

?

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

import java.util.concurrent.locks.reentrantlock;

 

public class reentrantlocktest2 {

  reentrantlock lock;

 

  reentrantlocktest2(reentrantlock lock) {

   this .lock = lock;

  }

 

  private runnable getrunnable() {

   return new runnable() {

    @override

    public void run() {

     while ( true ) {

      try {

       try {

        lock.lock();

//       lock.lockinterruptibly();

        system.out.println( "locked:" + thread.currentthread().getname());

        thread.sleep( 800 );

        break ;

       } finally {

        lock.unlock();

        system.out.println( "unlocked:" + thread.currentthread().getname());

       }

      } catch (interruptedexception e) {

       e.printstacktrace();

      }

     }

    }

   };

  }

 

  public static void main(string[] args) {

   reentrantlock lock = new reentrantlock();

   reentrantlocktest2 test = new reentrantlocktest2(lock);

   reentrantlocktest2 test2 = new reentrantlocktest2(lock);

   thread thread1 = new thread(test.getrunnable(), "firstthread" );

   thread thread2 = new thread(test2.getrunnable(), "secondthread" );

 

   thread1.start();

   thread2.start();

   try {

    thread.sleep( 600 );

   } catch (interruptedexception e) {

    e.printstacktrace();

   }

   system.out.println( "interupt begin" );

   thread2.interrupt();

   system.out.println( "interupt end" );

  }

}

一次执行结果

locked:firstthread
interupt begin
interupt end
unlocked:firstthread
locked:secondthread
unlocked:secondthread
java.lang.interruptedexception: sleep interrupted
    at java.lang.thread.sleep(native method)
    at com.jihite.templet.javabase.reentrantlocktest2$1.run(reentrantlocktest2.java:22)
    at java.lang.thread.run(thread.java:748)
locked:secondthread
unlocked:secondthread

分析:firstthread先获得锁执行,secondthread在等待,此时中断并未打断等待。firstthread执行完,secondthread获取后被打断

例子4

?

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

public class reentrantlocktest2 {

  reentrantlock lock;

 

  reentrantlocktest2(reentrantlock lock) {

   this .lock = lock;

  }

 

  private runnable getrunnable() {

   return new runnable() {

    @override

    public void run() {

     while ( true ) {

      try {

       try {

//       lock.lock();

        lock.lockinterruptibly();

        system.out.println( "locked:" + thread.currentthread().getname());

        thread.sleep( 800 );

        break ;

       } finally {

        lock.unlock();

        system.out.println( "unlocked:" + thread.currentthread().getname());

       }

      } catch (interruptedexception e) {

       e.printstacktrace();

      }

     }

    }

   };

  }

 

  public static void main(string[] args) {

   reentrantlock lock = new reentrantlock();

   reentrantlocktest2 test = new reentrantlocktest2(lock);

   reentrantlocktest2 test2 = new reentrantlocktest2(lock);

   thread thread1 = new thread(test.getrunnable(), "firstthread" );

   thread thread2 = new thread(test2.getrunnable(), "secondthread" );

 

   thread1.start();

   thread2.start();

   try {

    thread.sleep( 600 );

   } catch (interruptedexception e) {

    e.printstacktrace();

   }

   system.out.println( "interupt begin" );

   thread2.interrupt();

   system.out.println( "interupt end" );

  }

}

一次执行结果

locked:firstthread
interupt begin
interupt end
exception in thread "secondthread" java.lang.illegalmonitorstateexception
    at java.util.concurrent.locks.reentrantlock$sync.tryrelease(reentrantlock.java:151)
    at java.util.concurrent.locks.abstractqueuedsynchronizer.release(abstractqueuedsynchronizer.java:1261)
    at java.util.concurrent.locks.reentrantlock.unlock(reentrantlock.java:457)
    at com.jihite.templet.javabase.reentrantlocktest2$1.run(reentrantlocktest2.java:25)
    at java.lang.thread.run(thread.java:748)

分析:lock.lockinterruptibly();在执行过程中可以响应中断时间

以上所述是小编给大家介绍的java reentrantlock详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

查看更多关于java ReentrantLock详解的详细内容...

  阅读:10次