如何使Java函数原子操作,并防止计算主线程中断处理来自另一个线程的结果



这是我的计算函数,以及用于计算的对象表:

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
        }
    }
}

最新更新