我有一个非常简单的方案.下面的方法try 访问锁,等待1秒,最终释放锁.
private final Lock lock = new ReentrantLock();
public void lockAndWait() {
logger.info("I {} am here", Thread.currentThread().getName());
lock.lock();
try {
logger.info("I {} got the lock", Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
} finally {
lock.unlock();
}
}
我正在运行以下测试:
@Test
public void lockTest() {
for (int i = 0; i < 10; i++) {
new Thread(() -> lockAndWait()).start();
}
}
我得到了以下日志(log)输出:
12-10-2023 17:11:04 [Thread-2 ] INFO I Thread-2 am here
12-10-2023 17:11:04 [Thread-1 ] INFO I Thread-1 am here
12-10-2023 17:11:04 [Thread-6 ] INFO I Thread-6 am here
12-10-2023 17:11:04 [Thread-4 ] INFO I Thread-4 am here
12-10-2023 17:11:04 [Thread-8 ] INFO I Thread-8 am here
12-10-2023 17:11:04 [Thread-7 ] INFO I Thread-7 am here
12-10-2023 17:11:04 [Thread-5 ] INFO I Thread-5 am here
12-10-2023 17:11:04 [Thread-2 ] INFO I Thread-2 got the lock
12-10-2023 17:11:04 [Thread-3 ] INFO I Thread-3 am here
12-10-2023 17:11:04 [Thread-10 ] INFO I Thread-10 am here
12-10-2023 17:11:04 [Thread-9 ] INFO I Thread-9 am here
我不明白为什么只有一个线程,在本例中是Thread-2,可以访问锁.我原以为其余的线程都在等待lock.lock();
语句,一旦Thread-2释放了锁,其中一个线程就会得到它,直到所有线程都释放.如果我删除Thread.sleep(1000);
行,我期望发生的事情就会发生,但我不明白为什么.
我遗漏了什么?
SOLUTION个
根据Dhrubajyoti Gogoi的回答,我已经修改了我的测试方法,现在正在按预期工作.
@Test
public void policyUsageTest() throws InterruptedException {
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(() -> lockAndWait());
thread.start();
threads.add(thread);
}
for (Thread thread : threads) {
thread.join();
}
}
Output个
12-10-2023 18:08:14 [Thread-1 ] INFO I Thread-1 am here
12-10-2023 18:08:14 [Thread-5 ] INFO I Thread-5 am here
12-10-2023 18:08:14 [Thread-2 ] INFO I Thread-2 am here
12-10-2023 18:08:14 [Thread-9 ] INFO I Thread-9 am here
12-10-2023 18:08:14 [Thread-4 ] INFO I Thread-4 am here
12-10-2023 18:08:14 [Thread-7 ] INFO I Thread-7 am here
12-10-2023 18:08:14 [Thread-3 ] INFO I Thread-3 am here
12-10-2023 18:08:14 [Thread-8 ] INFO I Thread-8 am here
12-10-2023 18:08:14 [Thread-10 ] INFO I Thread-10 am here
12-10-2023 18:08:14 [Thread-6 ] INFO I Thread-6 am here
12-10-2023 18:08:14 [Thread-1 ] INFO I Thread-1 got the lock
12-10-2023 18:08:15 [Thread-2 ] INFO I Thread-2 got the lock
12-10-2023 18:08:16 [Thread-9 ] INFO I Thread-9 got the lock
12-10-2023 18:08:17 [Thread-5 ] INFO I Thread-5 got the lock
12-10-2023 18:08:18 [Thread-4 ] INFO I Thread-4 got the lock
12-10-2023 18:08:19 [Thread-3 ] INFO I Thread-3 got the lock
12-10-2023 18:08:20 [Thread-7 ] INFO I Thread-7 got the lock
12-10-2023 18:08:21 [Thread-8 ] INFO I Thread-8 got the lock
12-10-2023 18:08:22 [Thread-10 ] INFO I Thread-10 got the lock
12-10-2023 18:08:23 [Thread-6 ] INFO I Thread-6 got the lock