gpt4 book ai didi

对相同数据执行 Java 线程

转载 作者:行者123 更新时间:2023-11-29 03:41:58 28 4
gpt4 key购买 nike

首先是代码,大家可以复制粘贴

import java.util.ArrayList;

public class RepetionCounter implements Runnable{
private int x;
private int y;
private int[][] matrix;
private int xCounter;
private int yCounter;
private ArrayList<Thread> threadArray;
private int rowIndex;
private boolean[] countCompleted;

public RepetionCounter(int x, int y, int [][]matrix)
{
this.x = x;
this.y = y;
this.matrix = matrix;
this.threadArray = new ArrayList<Thread>(matrix.length);
this.rowIndex = 0;
for(int i = 0; i < matrix.length; i++){
threadArray.add(new Thread(this));
}
countCompleted = new boolean[matrix.length];
}

public void start(){
for (int i = 0; i < threadArray.size(); i++){
threadArray.get(i).start();
this.rowIndex++;
}
}

public void count(int rowIndex)
{
for(int i = 0; i < matrix[rowIndex].length; i++){
if (matrix[rowIndex][i] == x){
this.xCounter++;
} else if (matrix[rowIndex][i] == y){
this.yCounter++;
}
}
}

@Override
public void run() {
count(this.rowIndex);
countCompleted[this.rowIndex] = true;
}

public int getxCounter() {
return xCounter;
}

public void setxCounter(int xCounter) {
this.xCounter = xCounter;
}

public int getyCounter() {
return yCounter;
}

public void setyCounter(int yCounter) {
this.yCounter = yCounter;
}

public boolean[] getCountCompleted() {
return countCompleted;
}

public void setCountCompleted(boolean[] countCompleted) {
this.countCompleted = countCompleted;
}

public static void main(String args[]){
int[][] matrix = {{0,2,1}, {2,3,4}, {3,2,0}};
RepetionCounter rc = new RepetionCounter(0, 2, matrix);
rc.start();
boolean ready = false;
while(!ready){
for(int i = 0; i < matrix.length; i++){
if (rc.getCountCompleted()[i]){
ready = true;
} else {
ready = false;
}
}
}
if (rc.getxCounter() > rc.getyCounter()){
System.out.println("Thre are more x than y");
} else {System.out.println("There are:"+rc.getxCounter()+" x and:"+rc.getyCounter()+" y");

}
}

}

我想让这段代码做什么:我给对象一个矩阵和两个数字,我想知道这两个数字在矩阵中出现了多少次。我创建了与矩阵的行数一样多的线程(这就是为什么有那个 ArrayList),所以在这个对象中我有 k 个线程(假设 k 是行数),每个线程都计算两个线程的出现次数数字。问题是:如果我第一次运行它,一切正常,但如果我再次尝试执行它,我会得到 IndexOutOfBoundException,或者发生次数不正确,奇怪的是,如果我得到错误,并修改代码,之后它将再次运行一次。你能给我解释一下为什么会这样吗?

最佳答案

您正在为每个线程使用相同的 RepetitionCounter 实例:

for(int i = 0; i < matrix.length; i++){
threadArray.add(new Thread(this));
}

因此它们将共享相同的 rowIndex。代码非常困惑,所以我建议您将线程的逻辑封装在一个单独的 Runnable 类中,并带有单独的行 ID:

class ThreadTask implements Runnable {
private int rowId;
private int[][] matrix;

public ThreadTask(int[][] matrix, int rowId) {
this.matrix = matrix; // only a reference is passed here so no worries
this.rowId = rowId;
}

public void run() {
// search on my row
}
}

然后:

for(int i = 0; i < matrix.length; i++) {
threadArray.add(new Thread(new ThreadTask(matrix, i)));
}

关于对相同数据执行 Java 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12761043/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com