看好了,我只表演一次
/**
* 公平锁:ReentrantLock(true)
*
* 在大多数情况下,锁的申请都是非公平的。也就是说,线程1首先请求了锁A,接着线程2也请求了锁A。
* 那么当锁A可用时,是线程1还是线程2可以获得锁呢?显然这是不一定的。系统只会从这个锁的等待队列中随机挑选一个,因此不能保证其公平性。
*
* 公平锁会按照实际的先后顺序,保证先到先得,它不会产生饥饿,只要排队,最终都可以等到资源。
* 在创建重入锁时,通过有参构造函数,传入boolean类型的参数,true表示是公平锁。
* 实现公平所必然要维护一个有序队列,所以公平锁的实现成本高,性能相对也非常低,默认情况下,锁是非公平的。
*/
public class ReentrantLockExample3 implements Runnable{
//创建公平锁
public static ReentrantLock lock = new ReentrantLock(true);
static int i = 0;
@Override
public void run() {
for (int j = 0;j<5;j++){
lock.lock();
try {
i++;
System.out.println(Thread.currentThread().getName() + " 获得锁 " + i);
} finally {
lock.unlock();
}
}
}
public static void main(String[] a) throws InterruptedException {
ReentrantLockExample3 re = new ReentrantLockExample3();
Thread t1 = new Thread(re," 1 号线程 ");
Thread t2 = new Thread(re," 2 号线程 ");
Thread t3 = new Thread(re," 3 号线程 ");
Thread t4 = new Thread(re," 4 号线程 ");
t1.start();
t2.start();
t3.start();
t4.start();
/*
执行结果:
1 号线程 获得锁 1
2 号线程 获得锁 2
3 号线程 获得锁 3
4 号线程 获得锁 4
1 号线程 获得锁 5
2 号线程 获得锁 6
3 号线程 获得锁 7
4 号线程 获得锁 8
.....
4 号线程 获得锁 16
1 号线程 获得锁 17
2 号线程 获得锁 18
3 号线程 获得锁 19
4 号线程 获得锁 20
*/
}
}