所谓公平锁指的是哪个线程先运行,那就可以先得到锁。非公平锁是不管线程是否是先运行,都是随机获得锁的。
看下代码就清楚了。
<strong>package FairAndUnFailLock;
public class TestMain {
public TestMain() {
}
public static void main(String[] args) {
Service service = new Service();
ThreadClass tcArray[] = new ThreadClass[20];
for(int i=0;i<20;i++){
tcArray[i] = new ThreadClass(service);
tcArray[i].start();
}
}
}
package FairAndUnFailLock;
import java.util.concurrent.locks.ReentrantLock;
public class Service {
public ReentrantLock lock = new ReentrantLock(false);
public Service() {
}
public void getThreadName() {
System.out.println(Thread.currentThread().getName() + " 已经被锁定");
}
}
package FairAndUnFailLock;
public class ThreadClass extends Thread{
private Service service;
public ThreadClass(Service service) {
this.service = service;
}
public void run(){
System.out.println(Thread.currentThread().getName() + " 抢到了锁");
service.lock.lock();
service.getThreadName();
service.lock.unlock();
}
}
</strong>