公平锁:会按照线程启动的顺序,根据队列排序执行;非公平锁:新启动的线程有一定概率抢到刚释放的锁。
测试1
package practice.reentrantlock;
import java.util.concurrent.locks.ReentrantLock;
/**
* ReentrantLock公平锁和非公平锁测试1
* @author lbw
* @version 1.0
* @date 2020/11/25 11:28
*/
public class ReentrantLockTest {
//true公平锁;false非公平锁:执行到47时,有一定概率抢到31执行后的锁
static ReentrantLock reentrantLock = new ReentrantLock(true);
public static void main(String[] args) throws InterruptedException {
for(int i = 1; i < 51; i ++){
int finalI = i;
new Thread(() -> {
running("t" + finalI);
},"t" + finalI).start();
Thread.sleep(1);
}
}
private static void running(String threadName){
reentrantLock.lock();
System.out.println(threadName + "...");
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
reentrantLock.unlock();
}
}
}
测试1执行结果
说明:每个线程启动后sleep了1毫秒,所以线程启动有序的
1.当new ReentrantLock(true)设置为true时,打印出的结果为有序的。
2.当new ReentrantLock(false)设置为false时,线程47有一定概率抢到线程31结束后的锁。
测试2
package practice.reentrantlock;
import java.util.concurrent.locks.ReentrantLock;
/**
* ReentrantLock公平锁和非公平锁测试2
* @author lbw
* @version 1.0
* @date 2020/11/25 11:28
*/
public class ReentrantLockTest {
//true公平锁:会通过队列排队,执行running方法和线程启动顺序一致
//false非公平锁:只要锁被释放,就会争抢。执行running方法和线程启动顺序不同
static ReentrantLock reentrantLock = new ReentrantLock(true);
public static void main(String[] args) throws InterruptedException {
for(int i = 1; i < 51; i ++){
int finalI = i;
new Thread(() -> {
System.out.println("开始启动线程" + finalI);
running("t" + finalI);
},"t" + finalI).start();
}
}
private static void running(String threadName){
reentrantLock.lock();
System.out.println(threadName + "...");
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
reentrantLock.unlock();
}
}
}
测试2执行结果
1.当new ReentrantLock(true)设置为true时,running方法的执行和线程启动顺序一致。(都为2,3,1,4,5,7,8,9,10…)
2.当new ReentrantLock(false)设置为false时,running方法和线程启动顺序不同。(线程启动顺序为:1,3,4,2,5,6,7,8,9,10…;running方法的执行顺序为:3,29,45,4,2,1,5,6,7,8,9,10…)