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

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

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

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

        类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();
        }
    }
}

测试结果,公平锁


非公平锁



已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页