Lexi's Leetcode solutions

[knowledge] 两个不相关critical info的例子

Posted on: November 18, 2013

如果两个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) {

public void incrementC2 {


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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: