synchronized和ReentrantLock

参考文档

在JDK5.0之前,在协调对共享对象的访问时可以使用的机制只有synchronized和volatile.
JDK5.0新增了ReentrantLock,作为一种可选的高级功能.


  • ReentrantLock必须要在finally中unlock(), 否则,如果在被加锁的代码中抛出了异常,那么这个锁将会永远无法释放.
  • synchronized就没有这样的问题, 遇到异常退出时,会释放掉已经获得的锁.
    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
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    public class CannotRelease{
    static class OB{
    private static int count = 0;
    private ReentrantLock lock = new ReentrantLock();

    public void incre(){
    try{
    System.out.println("Execute incre()..........");
    lock.lock();
    System.out.println("Have get the lock!!!!");
    }finally{
    lock.unlock();
    }
    }

    public void cannotReleaseWhenException(){
    lock.lock();
    int[] arr = new int[2];
    System.out.println(arr[2]);
    /***
    * 這裏必須要finally裏面釋放鎖,否則發生異常,鎖便不能釋放
    */
    // finally
    // {

    System.out.println("unlllock");
    lock.unlock();
    //
    }
    }

    public synchronized void willReseaseWhenException()
    {

    int[] arr = new int[2];
    System.out.println(arr[2]);

    System.out.println(" willReseaseWhenException() endddddding ");

    }

    }

    public static void main(String[] ar)
    {
    OB on = new OB();

    new Thread(new Runnable()
    {

    @Override
    public void run()
    {
    /*
    * &*&** 先执行,并且获取了锁之后异常退出,没有释放锁<br>
    */
    // on.cannotReleaseWhenException();
    on.willReseaseWhenException();

    }

    }).start();

    new Thread(new Runnable()
    {

    @Override
    public void run()
    {
    /***
    * 后执行incre(),但是一直无法获取锁
    */
    on.incre();

    }

    }).start();


    }

    }