简体   繁体   中英

Share method local variable value between threads in java

I've been given the task to find the way to share a method's, involved in several threads, local variable, so it's value would be visible for every thread running this method.

Now my code look's like this:

public class SumBarrier2 implements Barrier {
    int thread_num;         // number of threads to handle
    int thread_accessed;    // number of threads come up the barrier
    volatile int last_sum;  // sum to be returned after new lifecyrcle
    volatile int sum;       // working variable to sum up the values

public SumBarrier2(int thread_num){
    this.thread_num = thread_num;
    thread_accessed = 0;
    last_sum = 0;
    sum = 0; 
}

public synchronized void addValue(int value){
    sum += value;
}

public synchronized void nullValues(){
    thread_accessed = 0;
    sum = 0;
}

@Override
public synchronized int waitBarrier(int value){
    int shared_local_sum;
    thread_accessed++;
    addValue(value);
    if(thread_accessed < thread_num){
        // If this is not the last thread
        try{
            this.wait();
        } catch(InterruptedException e){
            System.out.println("Exception caught");
        }
    } else if(thread_num == thread_accessed){
        last_sum = sum;
        nullValues();
        this.notifyAll();
    } else if (thread_accessed > thread_num ) {
        System.out.println("Something got wrong!");
    }       
    return last_sum;
}

}

So the task is to replace the class member

volatile int last_sum 

with method's waitBarrier local variable, so it's value would be visible to all threads.

Any suggestions? Is it even possible? Thanks in advance.

In case the variable last_sum is updated by only one thread, then declaring it volatile will work. If not then you should look at AtomicInteger

An int value that may be updated atomically. See the java.util.concurrent.atomic package specification for description of the properties of atomic variables. An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an Integer. However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes.

You can have the practical uses of AtomicInteger here: Practical uses for AtomicInteger

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM