21.重入锁ReentrantLock

ReentrantLock
    重入锁,在需要进行代码同步部分上加锁,但是一定要记得解锁。
    类型:公平锁(队列方式进行排队)、非公平锁(按照cpu的分配),非公平锁性能要比公平锁性能高,默认为非公平锁。
  1. package dmeo9;
  2. import javax.security.auth.login.FailedLoginException;
  3. import java.util.concurrent.locks.Lock;
  4. import java.util.concurrent.locks.ReentrantLock;
  5. /**
  6. * Created by liudan on 2017/8/4.
  7. */
  8. public class DemoLock {
  9. private Lock lock = new ReentrantLock(false);
  10. public void m1(){
  11. try {
  12. lock.lock();
  13. System.err.println(Thread.currentThread().getName()+":线程,进入m1");
  14. Thread.sleep(3000);
  15. System.err.println(Thread.currentThread().getName()+":线程,继续执行 m1");
  16. Thread.sleep(3000);
  17. } catch (InterruptedException e) {
  18. e.printStackTrace();
  19. }finally {
  20. lock.unlock();//解锁的动作写在finally内较好,因为解锁锁程序可能会发生一些意想不到的错误,导致无法正常解锁
  21. }
  22. }
  23. public void m2(){
  24. try {
  25. lock.lock();
  26. System.err.println(Thread.currentThread().getName()+":线程,进入m2");
  27. Thread.sleep(3000);
  28. System.err.println(Thread.currentThread().getName()+":线程,继续执行 m2");
  29. Thread.sleep(2000);
  30. } catch (InterruptedException e) {
  31. e.printStackTrace();
  32. }finally {
  33. lock.unlock();
  34. }
  35. }
  36. public static void main(String[] atgs){
  37. final DemoLock demoLock = new DemoLock();
  38. Thread t1 = new Thread(new Runnable() {
  39. @Override
  40. public void run() {
  41. demoLock.m1();
  42. demoLock.m2();
  43. }
  44. },"t_00001");
  45. t1.start();
  46. }
  47. } 输出:
  48. t_00001:线程,进入m1 t_00001:线程,继续执行 m1 t_00001:线程,进入m2 t_00001:线程,继续执行 m2
posted @ 2017-08-10 02:04  逍遥叹!!  阅读(203)  评论(0编辑  收藏  举报