公平锁表示线程获取锁的顺序是按照线程加锁的顺序来分配的,即先来先得的FIDO先进先出顺序.
非公平锁就是一种获取锁的抢占机制,是随机获得锁的.
public class DemoService {
private Lock lock;
public DemoService(Boolean isFair) {
this.lock = new ReentrantLock(isFair);
}
public void print() {
lock.lock();
try {
System.out.println("ThreadName=" + Thread.currentThread().getName() + "锁定");
} finally {
lock.unlock();
}
}
}
public class Test {
public static void main(String[] args) {
DemoService service = new DemoService(true);
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Thread:" + Thread.currentThread().getName());
service.print();
}
};
Thread[] thread = new Thread[10];
for (int i = 0; i < 10; i++) {
thread[i] = new Thread(runnable);
}
for (int i = 0; i < 10; i++) {
thread[i].start();
}
}
}
image.png
打印的结果基本呈有序状态,这就是公平锁的特点。
将Test类中的ture改为false就变成了非公平锁了:
image.png
非公平锁运行结果基本是乱序的,说明先start的线程不一定先获得锁。
网友评论