ReentrantLock 重入锁

来源:互联网 发布:手机必备软件大全 编辑:程序博客网 时间:2024/05/01 16:01
/** * ReentrantLock 重入锁 * Re-Entrant-lock  * 对于某一个线程可以反复给该线程加锁 * 但是记得释放锁,要不会产生死锁 * @author beiyaoyao * */public class ReenterLock implements Runnable {    public static int i = 1;    //重入锁    public static ReentrantLock instance = new ReentrantLock();    @Override    public void run() {        for(int j = 0 ; j < 2000 ; j ++){                instance.lock();            try{                i++;                System.out.println(Thread.currentThread().getName());            }finally{                instance.unlock();            }        }    }    public static void main(String[] args) throws InterruptedException {        ReenterLock tl = new ReenterLock();        Thread t1 = new Thread(tl,"Thread_1");        Thread t2 = new Thread(tl,"Thread_2");        t1.start();        t2.start();        t1.join();        t2.join();        System.out.println(i);    }}

当给ReentrantLock对象传入参数true时,表示锁是公平的。由于公平锁实现成本比较高,在默认情况下,锁是非公平的。

public static ReentrantLock instance = new ReentrantLock(true);

当使用非公平锁的时候,输出如下:
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_2
Thread_2
Thread_2
Thread_2
Thread_2
Thread_2
Thread_2

一个线程会有很大可能再次获得已经获得过的锁。

如果使用公平锁
Thread_1
Thread_2
Thread_1
Thread_2
Thread_1
Thread_2
Thread_1
线程基本上是在交替获得锁,几乎不发生同一个线程连续获得两次锁的可能。

0 0