class Entry
{
public Entry(String value){
this.value = value;
System.out.println("[Entry]setValue:"+value);
}
private String value = "";
public String getValue()
{
System.out.println("[Entry]getValue"+value);
return value;
}
public Entry setValue(String value)
{
this.value = value;
System.out.println("[Entry]setValue:"+value);
return this;
}
}
private static Entry testTryFinally()
{
Entry e = new Entry("0");
try{
return e.setValue("2");
}finally{
e.setValue("1");
}
}
public static void main(String[] args) throws IOException
{
testTryFinally();
}
输出结果: [Entry]setValue:0 [Entry]setValue:2 [Entry]setValue:1
结论:
先执行Entry e = new Entry("0");
再执行e.setValue("2");然后把这一步的值赋给return,这个时候进入finally
再执行e.setValue("1");
在执行finally之前e.setValue("2");就已经执行了,然后把结果暂存在return里面.
执行完finally后才返回return.
r.lock();
try{
return Entry.setValue("X");
}finally{
r.unlock();
}
这段代码是线程安全的,因为先执行了Entry.setValue("X");才解锁的.