[英]How to make Java function atomic operation, and prevent calculation main thread interruption for handing results from another thread
这是我的计算函数,也是我用于计算的对象表:
public class Calculator{
private Table table = new DefaultTable();
// calls in UI thread onButtonPressed
public Result calculate(){
// do some calculation here with table
// return Result here
}
// calls from Handler.handleMessage() when newtable ready to use
public void setTable(Table newtable){
this.table = newtable
}
}
在Calculate()
运行时,如何防止更改表?
您应该在同一监视器上同步两个对象。 如果这些是你需要同步的只有两个方法,你可以使用this
为您的显示器,这是什么synchronized
修改隐含的作用:
public class Calculator{
private Table table = new DefaultTable();
public synchronized Result calculate(){
// implementation
}
public synchronized void setTable(Table newtable){
this.table = newtable
}
}
为了获得更细粒度的控件,您可以定义自己的锁定对象:
public class Calculator{
private final Object monitor = new Object();
private Table table = new DefaultTable();
public Result calculate() {
synchronize (monitor) {
// implementation
}
}
public void setTable(Table newtable){
synchronize (monitor) {
this.table = newtable
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.