ReentrantLock的公平锁与非公平锁。

package com.xiangwen.day3;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockFaieTest {
    public static void main(String[] args) {
        Thread[] threads=new Thread[10];
        Service s=new Service(false);
        Runnable runnable=new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"开始运行!");
                s.lockMeth();
            }
        };
        for(int i=0;i<10;i++){
            threads[i]=new Thread(runnable);
        }
        for(int i=0;i<10;i++){
            threads[i].start();
        }
    }
}
class Service{
    ReentrantLock reentrantLock;
    public Service(boolean flg){
        reentrantLock=new ReentrantLock(flg);
    }
    public void lockMeth(){
        reentrantLock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"==获取锁定!");
        }finally {
            reentrantLock.unlock();
        }

    }
}

 

 线程7是倒数第二开始运行,但是第三获取的锁,不公平锁,获取锁的概率是随机的。

posted @ 2021-05-25 13:56  傲云萧雨  阅读(62)  评论(0编辑  收藏  举报