【问题标题】:Share method local variable value between threads in java在java中的线程之间共享方法局部变量值
【发布时间】:2014-04-27 04:23:50
【问题描述】:

我的任务是找到共享方法的方法,涉及多个线程,局部变量,因此它的值对于运行此方法的每个线程都是可见的。

现在我的代码如下所示:

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

}

所以任务是替换类成员

volatile int last_sum 

带有方法的waitBarrier局部变量,所以它的值对所有线程都是可见的。

有什么建议吗? 甚至可能吗? 提前致谢。

【问题讨论】:

标签: java multithreading variables shared barrier


【解决方案1】:

如果变量last_sum 仅由一个线程更新,则声明它volatile 将起作用。如果没有,那么你应该看看AtomicInteger

可以自动更新的 int 值。见 java.util.concurrent.atomic 包规范的描述 原子变量的属性。 AtomicInteger 用于 应用程序,如原子递增的计数器,并且不能 用作整数的替代品。但是,这个类确实扩展了 允许处理的工具和实用程序统一访问的编号 基于数字的类。

AtomicInteger的实际用途可以在这里:Practical uses for AtomicInteger

【讨论】:

    猜你喜欢
    • 2021-12-11
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    相关资源
    最近更新 更多