View Code? Open in Web Editor
NEW
A clean, elegant blog built on Rust
Home Page: https://web.archive.org/web/20220818011125/http://0x709394.me/
Rust 21.55%
CSS 25.31%
JavaScript 46.97%
Dockerfile 0.24%
PLpgSQL 0.62%
Less 5.31%
blog's People
blog's Issues
您好,我阅读了您的文章《一条经典面试题引发的思考》 之后对一些地方有异议,由于没在博客中找到评论的地方,所以冒昧将问题写在了这里,打扰之处,还请谅解。
问题描述
请问 第23行,在 continue 之前是否需要先执行 Unlock
操作。否则可能出现锁资源未释放的情况。
具体分析如下,我们将i
的上限从30改成3,这样相当于希望每个线程只执行一次有效操作。
假设有这样的情况,线程 B 执行一次后,线程 C 正在上锁,此时i
的值还没改变,线程 B判断i < 3
继续循环。线程 C 执行成功后,线程 B加锁成功。此时i
变成了3,线程 B 判断i >= 3
,结束循环,线程 B 就有了一个加锁的锁资源未释放。
1 public void Test (){
2 private static Integer index = 0 ;
3 Lock lock = new ReentrantLock (true );
4 @ Test
5 public void testLock (){
6 Thread threadA = work (() -> System .out .println ("A" ));
7 Thread threadB = work (() -> System .out .println ("B" ));
8 Thread threadC = work (() -> System .out .println ("C" ));
9 threadA .setName ("threadA" );
10 threadA .start ();
11 threadB .setName ("threadB" );
12 threadB .start ();
13 threadC .setName ("threadC" );
14 threadC .start ();
15 System .out .println ();
16 }
17
18 private Thread work (Runnable function ) {
19 return new Thread (() -> {
20 while (index .intValue () < 3 ) {
21 lock .lock ();
22 if (index >= 3 ) {
23 // lock.unlock();
24 continue ;
25 }
26 if (condition .test (index .intValue ())) {
27 function .run ();
28 index ++;
29 }
30 lock .unlock ();
31 }
32 });
33 }
34 }
error: could not find Cargo.toml
in /usr/local/src
or any parent directory
Hi Ramsay,
The initial login username and password seems not working at the moment. May I ask where can I find the correct one?
BTW, I guess the server port has been changed to 1337.
Thank you.