ReentrantLock在创建Lock对象时会提供boolean fair
标志。fair
:true
根据线程等待的时间,它们可以访问关键部分。fair
:false
没有为线程提供关键部分的特定策略。
下面是我的相同代码:
public class ThreadDemo {
private Lock lock = new ReentrantLock(false);
public static void main(String[] args) {
ThreadDemo td = new ThreadDemo();
Thread[] tArr = new Thread[5];
// Creates 5 thread and stores them in a array
for (int i = 0; i < 5; i++) {
tArr[i] = new Thread(() -> {
td.enterCriticalSection(new Date().getTime());
}, "Thread " + i);
}
// Iterate through the array and start it.
for (int i = 0; i < 5; i++) {
tArr[i].start();
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void enterCriticalSection(long waitTime) {
System.out.println(Thread.currentThread().getName() + " requesting critical section at:"
+ new SimpleDateFormat("HH:mm:ss:SSS").format(new Date().getTime()));
// Gets Lock
lock.lock();
try {
/*
* Logs the entry time in critical section and waiting period for
* the thread
*/
System.out.println(Thread.currentThread().getName() + " in critical section at "
+ new SimpleDateFormat("HH:mm:ss:SSS").format(new Date().getTime()));
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// Releases lock
lock.unlock();
}
}
}
但是对于真假和假假我都得到相同的结果,即等待时间最长的线程获得了关键部分
Thread 0 requesting critical section at:01:57:48:562
Thread 0 in critical section at 01:57:48:563
Thread 1 requesting critical section at:01:57:49:520
Thread 2 requesting critical section at:01:57:50:520
Thread 3 requesting critical section at:01:57:51:520
Thread 4 requesting critical section at:01:57:52:520
Thread 1 in critical section at 01:57:53:564
Thread 2 in critical section at 01:57:58:564
Thread 3 in critical section at 01:58:03:565
Thread 4 in critical section at 01:58:08:566
最佳答案
所有fair false
的意思是,锁将根据需要允许线程进入。如果线程数量很少,则可能恰好是它们一直在等待的顺序,但是并不能对此做出任何保证。