[英]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.