今天学习了一下关于Lock中的公平锁和非公平锁,就想总结一下这两种之间的区别。具体有不对的地方欢迎指正。
首先锁Lock分为"公平锁"和"非公平锁",公平锁表示线程获取锁的顺序是按照线程加锁的顺序来分配的,即呢就是先来先得的FIFO先进先顺序。非公平锁就是获取锁的抢占机制,是随机获取锁的,那这俩货的区别就在这个地方了,非公平锁先来的不一定先得到锁,这就会造成某些线程可能一直拿不到锁,结果自然就是不公平。
可以看下代码来区别一下:
import java.util.concurrent.locks.ReentrantLock;
/**
* 公平锁与不公平锁的区别
*
*
*/
public class Service {
private ReentrantLock lock;
public Service(boolean isFair){
lock = new ReentrantLock(isFair);
}
public void serviceMethod(){
try{
lock.lock();//获取同监视器
System.out.println("ThreadName = "+Thread.currentThread().getName()+"获得锁定");
}finally{
lock.unlock();
}
}
}
测试类---公平锁
public class RunFairTest {
/**
* @param args
*/
public static void main(String[] args) {
final Service service = new Service(true);
Runnable run = new Runnable(){
@Override
public void run() {
System.out.println("***** = "+Thread.currentThread().getName()+"运行了");
service.serviceMethod();
}
};
//10个线程运行
Thread[] ts = new Thread[10];
for(int i=0;i<10;i++){
ts[i]= new Thread(run);
}
for(int i=0;i<10;i++){
ts[i].start();
}
}
}
运行结果是:
***** = Thread-0运行了
***** = Thread-4运行了
***** = Thread-3运行了
***** = Thread-2运行了
***** = Thread-1运行了
ThreadName = Thread-0获得锁定
***** = Thread-5运行了
***** = Thread-7运行了
***** = Thread-6运行了
ThreadName = Thread-4获得锁定
***** = Thread-9运行了
***** = Thread-8运行了
ThreadName = Thread-3获得锁定
ThreadName = Thread-2获得锁定
ThreadName = Thread-1获得锁定
ThreadName = Thread-5获得锁定
ThreadName = Thread-7获得锁定
ThreadName = Thread-6获得锁定
ThreadName = Thread-9获得锁定
ThreadName = Thread-8获得锁定
从运行结果可以看出,以*****开始的线程顺序是:0,4,3,2,1,5,7,6,9,8
以ThreadName 开头的顺序也是:0,4,3,2,1,5,7,6,9,8
打印的结果是呈有序状态。
测试类中true改为false,
再看控制台结果输出,
***** = Thread-0运行了
***** = Thread-3运行了
***** = Thread-2运行了
***** = Thread-1运行了
***** = Thread-5运行了
***** = Thread-6运行了
***** = Thread-7运行了
ThreadName = Thread-3获得锁定
***** = Thread-9运行了
ThreadName = Thread-2获得锁定
ThreadName = Thread-1获得锁定
***** = Thread-4运行了
ThreadName = Thread-5获得锁定
ThreadName = Thread-6获得锁定
***** = Thread-8运行了
ThreadName = Thread-7获得锁定
ThreadName = Thread-9获得锁定
ThreadName = Thread-0获得锁定
ThreadName = Thread-4获得锁定
ThreadName = Thread-8获得锁定
基本上是乱序的,
从上就可以说明先启动start的不代表先获取锁