簡體   English   中英

如何使Java函數實現原子操作,並防止計算主線程中斷以處理來自另一個線程的結果

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM