package com.freeflying.thread.reentrantlock;
import java.util.concurrent.locks.ReentrantLock;
public class FairAndNoFair {
public static void main(String[] args) {
final FairAndNoFairEx fEx=new FairAndNoFairEx(false);
Runnable runnable=new Runnable() {
@Override
public void run() {
System.out.println("ThreadA:"+Thread.currentThread().getName()+" is running");
fEx.method();
}
};
Thread[] threads=new Thread[10];
for (int i = 0; i < threads.length; i++) {
threads[i]=new Thread(runnable);
}
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
}
}
class FairAndNoFairEx{
private ReentrantLock lock;
public FairAndNoFairEx(boolean isFair) {
super();
lock=new ReentrantLock(isFair);
}
public void method() {
try {
lock.lock();
System.out.println("ThreadName:"+Thread.currentThread().getName()+"get lock");
} finally {
lock.unlock();
}
}
}
结果:
ThreadA:Thread-3 is running
ThreadA:Thread-7 is running
ThreadName:Thread-3get lock
ThreadName:Thread-7get lock
ThreadA:Thread-1 is running
ThreadName:Thread-1get lock
ThreadA:Thread-9 is running
ThreadName:Thread-9get lock
ThreadA:Thread-5 is running
ThreadName:Thread-5get lock
ThreadA:Thread-2 is running
ThreadName:Thread-2get lock
ThreadA:Thread-6 is running
ThreadName:Thread-6get lock
ThreadA:Thread-0 is running
ThreadA:Thread-4 is running
ThreadName:Thread-4get lock----这里明显有乱序
ThreadName:Thread-0get lock----
ThreadA:Thread-8 is running
ThreadName:Thread-8get lock