开发者

Android - Accessing a variable in Activity (Using synchronization)

开发者 https://www.devze.com 2023-02-24 07:59 出处:网络
I have a question in synchronization between threads in Android. What I have is: 2 thre开发者_Python百科ad spawned from an activity, and each of this thread is accessing a field in the activity simu

I have a question in synchronization between threads in Android.

What I have is:

2 thre开发者_Python百科ad spawned from an activity, and each of this thread is accessing a field in the activity simultaneously.

What I am thinking of is to use synchronize, such as

synchronize private void functionA()  

or

synchronize(mContext){  
....  
}  

(where mContext is context of activity)

But I am not sure if it will really work.

Or does anyone has any better ideas?

Thanks.


here's a pretty good example - you make the variable private and then create synchronized getter and setter functions:

class Account {
    private double balance;             // make variable private

    // write synchronized accessor methods
    public synchronized void setBalance(double b) {
        balance = b;
    }

    public synchronized double getBalance() {
        return balance;
    }

    // modify update method to use accessor methods
    synchronized void updateBalance(double amount) {
    //    double b = getBalance();
        setBalance( getBalance() + amount);
    }
}

source: http://www.janeg.ca/scjp/threads/synchronized.html

and here's another example, this time using ArrayList: http://www.vogella.de/articles/JavaConcurrency/article.html#concurrencyjava_synchronized


The synchronize can do this and make the thread synchronously.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号