Tem*_*ing 13 java concurrency multithreading
示例代码:
class Sample{
private int v;
public void setV(){
Lock a=new Lock();
a.lock();
try{
v=1;
}finally{
a.unlock();
}
}
public int getV(){
return v;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我有一个线程不断调用getV而我只是在另一个线程中执行setV一次,那么读取线程是否保证在写入后立即看到新值?或者我需要使"V"易失或AtomicReference?
如果答案是否定的,那么我应该将其更改为:
class Sample{
private int v;
private Lock a=new Lock();
public void setV(){
a.lock();
try{
v=1;
}finally{
a.unlock();
}
}
public int getV(){
a.lock();
try{
int r=v;
}finally{
a.unlock();
}
return r;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1876 次 |
最近记录: |