Lexi's Leetcode solutions

Archive for the ‘knowledge’ Category

如果两个field没关系,可以生成两个锁,这样update c1必须是synchronized, c2也是。但是要是直接synchronize两个函数,说明update c1的时候c2也得干瞅着,浪费了。就跟reader writer类似,read的时候另一个reader明明也可以read的,但要是完全上锁,则read, write都要等别人了。

public class Foo {
ReentrantLock L1 = new ReentrantLock();
ReentrantLock L2 = new ReentrantLock();
int c1, c2;

public void incrementC1 {
synchronized(L1) {
c1++;
}
}

public void incrementC2 {
L2.lock();
c2++;
L2.unlock();
}
}

 

一种用lock,一种用synchronized object的区别就是,用lock的可以手动处理c2++ throw exception的情况,而用synchronized出了scope索就自动丢了。


Blog Stats

  • 222,875 hits
March 2023
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031