【发布时间】:2023-03-26 11:06:01
【问题描述】:
所以我需要使用线程(已经拆分)处理几个数据文件,并且我在如何停止主线程直到所有子线程完成时遇到问题。 我环顾四周并尝试使用 join() 但这会导致问题:
- 如果我加入主线程和最后一个线程,那么由于其他线程同时运行,最后一个线程并不总是最后一个完成
- 如果我将主线程与所有其他线程一起加入,那么它们不会同时运行,第二个需要第一个先完成。 还尝试了 wait() 和 notify() 但有更多问题。这是我的代码的一部分
public class Matrix extends MapReduce {
ArrayList<String> VecteurLines = new ArrayList<String>();
protected int[] nbrLnCol = {0,0};
protected static double[] res;
public Matrix(String n) {
super(n);
}
public Matrix(String n,String m){
super(n,m);
}
public void Reduce() throws IOException, InterruptedException, MatrixException {
for (int i = 1; i <= Chunks; i++) {
Thread t=new Thread(new RunThread(VecteurLines,i,this));
t.start();
}
}
这是处理线程的类
public class RunThread extends Matrix implements Runnable {
Matrix ma;
ArrayList<String> vec;
int threadNbr;
public RunThread(ArrayList<String> vec, int threadNbr,Matrix ma) {
super("","");
this.vec=vec;this.threadNbr=threadNbr;this.ma=ma; }
@Override
public void run() {
FileInputStream fin = null;
try {
fin = new FileInputStream(ma.getNom()+threadNbr+".txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Scanner sc = new Scanner(fin);
while (sc.hasNext()) {
String nextString = sc.next();
ma.nbrLnCol[0]++;
String [] arr = nextString.split(",");
ma.nbrLnCol[1]=arr.length;
double c=0;
for(int j=0;j<arr.length;j++)
{
c+=(Double.parseDouble(arr[j])*Double.parseDouble(vec.get(j)));
}
res[threadNbr-1]=c;
}
sc.close();
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
File file = new File(ma.getNom()+threadNbr+".txt");
file.delete();
}
【问题讨论】:
-
显而易见的解决方案是加入所有子线程,但我在您的代码中看不到 join()。
-
我删除了它,因为它最终会一个接一个地运行线程,而不是同时运行所有线程
-
join不应导致任何线程延迟。你到底尝试了什么?主线程中发生了什么?看起来RunThread在每个线程中都执行了一些操作,但是您提供的代码除了启动一系列线程之外,没有任何线程管理。 -
@Ayman Elya join() 不会让线程一一运行。有不同的原因。
-
那段代码,有一个错误,但在我们得到代码之前我们无法修复它。
标签: java multithreading java-threads