重入锁ReentrantLock之公平锁与非公平锁

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/javabird945/article/details/80566596

        公平锁:线程获取锁的顺序是按照线程加锁的顺序来分配的,即先进先出。

        非公平锁:线程获取锁的顺序是随机的,听天由命。

        怎样构建公平锁与非公平锁?

        类ReentrantLock有两个构造方法,其中一个是传递一个boolean类型的参数,标识创建一个具有给定公平策略的ReentrantLock,即:

1. 创建公平锁或非公平锁

public class TestPolicyLock {

    private ReentrantLock reentrantLock;

    public TestPolicyLock(boolean lock){
        super();
        reentrantLock = new ReentrantLock(lock);
    }

    public void printMsg(){
        try{
            reentrantLock.lock();
            System.out.println("Thread---" + Thread.currentThread().getName() + "---Get Lock");
        } finally {
            reentrantLock.unlock();
        }

    }
}
public class TestPolicyLockThread extends Thread {

    private TestPolicyLock testPolicyLock;

    public TestPolicyLockThread(TestPolicyLock testPolicyLock){
        super();
        this.testPolicyLock = testPolicyLock;
    }

    @Override
    public void run(){
        System.out.println("Thread---" + Thread.currentThread().getName() + "---Begin");
        testPolicyLock.printMsg();
    }
}
public class TestPolicyLockMain {

    public static void main(String[] args){

        TestPolicyLock testPolicyLock = new TestPolicyLock(true);
//        TestPolicyLock testPolicyLock = new TestPolicyLock(false);

        for(int i = 0; i < 10; i++){

            Thread thread = new TestPolicyLockThread(testPolicyLock);
            thread.setName(String.valueOf(i));
            thread.start();
        }
    }
}

测试结果,公平锁


非公平锁



展开阅读全文

没有更多推荐了,返回首页