公平锁与非公平锁

/ 多线程 热门推荐 / 没有评论 / 315浏览

下面我们用两个例子来演示一下公平锁与非公平锁。

公平锁

/**
* 用户登录
*
* @author Sama
* @author admin@jilinwula.com
* @date 2017-03-15 10:35
* @since 1.0.0
*/
public class Userinfo {

private ReentrantLock lock;

public Userinfo(boolean fair) {
lock = new ReentrantLock(fair);
}

public void test() {
lock.lock();
System.out.println(String.format("线程获取锁\tthread: %s", Thread.currentThread().getName()));
lock.unlock();
}
}
/**
* 管理用户请求
*
* @author Sama
* @author admin@jilinwula.com
* @date 2017-03-15 10:44
* @since 1.0.0
*/
public class RequestAdmin extends Thread {

private Userinfo userinfo;


public RequestAdmin(Userinfo userinfo) {
this.userinfo = userinfo;
}

@Override
public void run() {
System.out.println(String.format("线程运行了\tthread: %s", Thread.currentThread().getName()));
userinfo.test();
}
}
/**
* @author Sama
* @author admin@jilinwula.com
* @date 2017-03-20 13:35
* @since 1.0.0
*/
public class Test {
public static void main(String[] args) throws InterruptedException {
Userinfo userinfo = new Userinfo(true);
RequestAdmin[] requestAdmins = new RequestAdmin[10];
for (int i = 0; i < 10; i++) {
requestAdmins[i] = new RequestAdmin(userinfo);
}
for (int i = 0; i < 10; i++) {
requestAdmins[i].start();
}
}
}
线程运行了	thread: Thread-5
线程运行了	thread: Thread-4
线程获取锁	thread: Thread-5
线程运行了	thread: Thread-9
线程运行了	thread: Thread-2
线程运行了	thread: Thread-0
线程运行了	thread: Thread-6
线程运行了	thread: Thread-8
线程运行了	thread: Thread-3
线程获取锁	thread: Thread-4
线程运行了	thread: Thread-1
线程获取锁	thread: Thread-9
线程获取锁	thread: Thread-2
线程运行了	thread: Thread-7
线程获取锁	thread: Thread-0
线程获取锁	thread: Thread-6
线程获取锁	thread: Thread-8
线程获取锁	thread: Thread-3
线程获取锁	thread: Thread-1
线程获取锁	thread: Thread-7

我们看输出线程的运行顺序和线程获取锁的顺序是一致的。这就是公平锁的特征,先到先得。下面我们看一下非公平锁。

非公平锁

我们只需要将测试类中的Userinfo对象的参数为true改成false即可。

/**
* @author Sama
* @author admin@jilinwula.com
* @date 2017-03-20 13:35
* @since 1.0.0
*/
public class Test {
public static void main(String[] args) throws InterruptedException {
Userinfo userinfo = new Userinfo(false);
RequestAdmin[] requestAdmins = new RequestAdmin[10];
for (int i = 0; i < 10; i++) {
requestAdmins[i] = new RequestAdmin(userinfo);
}
for (int i = 0; i < 10; i++) {
requestAdmins[i].start();
}
}
}
线程运行了	thread: Thread-5
线程运行了	thread: Thread-3
线程运行了	thread: Thread-6
线程获取锁	thread: Thread-5
线程运行了	thread: Thread-8
线程运行了	thread: Thread-0
线程获取锁	thread: Thread-8
线程运行了	thread: Thread-7
线程运行了	thread: Thread-4
线程获取锁	thread: Thread-7
线程获取锁	thread: Thread-3
线程获取锁	thread: Thread-6
线程获取锁	thread: Thread-0
线程获取锁	thread: Thread-4
线程运行了	thread: Thread-1
线程获取锁	thread: Thread-1
线程运行了	thread: Thread-2
线程获取锁	thread: Thread-2
线程运行了	thread: Thread-9
线程获取锁	thread: Thread-9

我们看线程获取锁的顺序和线程的执行顺序没有什么规律,这就是非公平锁,不能保证,先执行的线程一定能够先获得到锁。

  1. 公平锁的性能要比非公平锁的性能要低
  2. ReentrantLock类默认的构造参数为false也就是默认是非公平锁