0

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

现在我的代码看起来像这样:

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 局部变量,因此它的值对所有线程都是可见的。

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

4

1 回答 1

0

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

可以自动更新的 int 值。有关原子变量属性的描述,请参阅 java.util.concurrent.atomic 包规范。AtomicInteger 用于原子递增计数器等应用程序,不能用作 Integer 的替代品。但是,此类确实扩展了 Number 以允许处理基于数字的类的工具和实用程序进行统一访问。

您可以在AtomicInteger这里获得实际用途:AtomicInteger的实际用途

于 2014-03-20T11:14:30.070 回答