有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java原子整数错误行为

我有一个练习:给定一个原子整数矩阵(初始化为0),我必须为每一行运行一个线程,为每一列运行一个线程,在我减去1的行上,在我加1的列上,所以最后矩阵应该保持原样。问题是矩阵改变了!代码如下: 对象获取矩阵,一个布尔值,它将告诉他对列或行进行操作,以及它必须操作的列/行的索引

import java.util.concurrent.atomic.AtomicInteger;

public class FifthExerciseSafe implements Runnable{
    private Thread thread;
    private boolean onRows;//tells if the object operates on the rows or on the columns
    private AtomicInteger[][] matrix;
    private int index;

public FifthExerciseSafe(AtomicInteger[][] matrix, boolean onRows, int index){
    this.matrix = matrix;
    this.onRows = onRows;
    this.index = index;
}

public void start(){
    thread = new Thread(this);
    thread.start();
}

public boolean isOnRows() {
    return onRows;
}

public void setOnRows(boolean onRows) {
    this.onRows = onRows;
}

public AtomicInteger[][] getMatrix() {
    return matrix;
}

public void setMatrix(AtomicInteger[][] matrix) {
    this.matrix = matrix;
}

@Override
public void run() {
    if (this.onRows){
        for(int i = 0; i < matrix[index].length; i++){
            matrix[index][i].decrementAndGet();
        }
    } else {            
        for(int i = 0; i < matrix.length; i++){
            matrix[i][index].incrementAndGet();
        }
    }
}//run

public static void main(String args[]){
    AtomicInteger[][] m = new AtomicInteger[3][3];
    for (int i = 0; i < m.length; i++){
        for(int j = 0; j < m.length; j++){
            m[i][j]= new AtomicInteger(0);
        }
    }

    for(int i = 0; i < 3; i++){//I create 6 objects, 3 for columns and 3 for rows
        FifthExerciseSafe fes1 = new FifthExerciseSafe(m, true, i);
        FifthExerciseSafe fes2 = new FifthExerciseSafe(m, false, i);
        fes1.start();
        fes2.start();
    }
    for(int i = 0; i < m.length; i++){
        for(int j = 0; j < m.length; j++){
            System.out.print(m[i][j]+" ");
        }
    }
}//main
}

输出应为: 000000 但有时是: -100-100-1-10

这种情况只发生在装有Intel Atom的上网本上,在装有Core Duo的台式机上我还没见过,但我想知道这种情况是否也会发生在那里


共 (1) 个答案

  1. # 1 楼答案

    您已经开始了线程,但是在继续打印矩阵之前,您从不等待线程完成。您需要为每个启动的线程使用Thread.join,它将阻塞,直到线程完成。只有这样才能安全地打印出结果。例如,引入一个ArrayList,将启动的Thread的所有实例add放入其中,然后在每个实例上有一个单独的for循环来调用join