gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:34:45 25 4
gpt4 key购买 nike

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

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

关于java - 如何使Java函数原子操作,并防止计算主线程因另一个线程处理结果而中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35559655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com