0

我有一个练习:给定一个 AtomicIntegers 矩阵(初始化为 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 的台式机上我还没有看到它,但我想知道它是否也会发生在那里。

4

1 回答 1

6

You have started the threads, but you never wait for them to finish before going on to print out the matrix. You need to use Thread.join for each started thread, which will block until the thread is done. Only then will it be safe to print out the results. For example, introduce an ArrayList into which you add all the instances of Thread you start, and then have a separate for loop that invokes join on each instance.

于 2012-11-20T10:20:15.120 回答