示例:
public class Test4 {
public static void main(String[] args) {
TestReentrantlock test = new TestReentrantlock();// ReentrantLock有公平性
// TestSync test = new TestSync(); synchronized没有公平性
Thread t1 = new Thread(test);
Thread t2 = new Thread(test);
t1.start();
t2.start();
}
}
class TestReentrantlock extends Thread {
// 向构造方法中传入true,定义一个公平锁
private static ReentrantLock lock = new ReentrantLock(true);
public void run() {
for (int i = 0; i < 5; i++) {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + " get lock");
} finally {
lock.unlock();
}
}
}
}
class TestSync extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
synchronized (this) {
System.out.println(Thread.currentThread().getName() + " get lock in TestSync");
}
}
}
}