gpt4 book ai didi

java - java中的同步——new ReentrantLock(true)和new ReentrantLock(false)产生相同的结果?

转载 作者:行者123 更新时间:2023-12-02 03:04:36 27 4
gpt4 key购买 nike

ReentrantLock 在创建 Lock 对象时提供 boolean fair 标志。

  1. 公平:真实

    线程根据其等待的时间来访问临界区。

  2. 公平:

    没有为线程提供临界区的具体策略。

下面是我的代码:

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的意思是锁将让线程以任何它想要的方式进入。对于少量线程,它可能恰好是它们一直在等待的顺序,但它并不能对此做出任何保证。

关于java - java中的同步——new ReentrantLock(true)和new ReentrantLock(false)产生相同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41914555/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com