我有一个练习:给定一个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
它只发生在配备英特尔凌动处理器的上网本上,在配备Core Duo的台式机上,我还没有见过,但我想知道它是否也会在那里发生。
发布于 2012-11-20 18:20:15
您已经启动了线程,但在继续打印矩阵之前,您从不等待它们完成。例如,引入一个ArrayList,在其中add您启动的所有Thread实例,然后有一个单独的for循环,该循环在每个实例上调用join。
https://stackoverflow.com/questions/13471036
复制相似问题