我想使用多个线程处理数据,但目前只有第一个线程运行,然后它完全停止。
我试图打印出Threads的名字,但我只输入第一个Thread。即使程序继续运行,它也会停止。它转到synchpoint.await()
然后停止。
public class Solver {
final int N;
final float[][] data;
final CyclicBarrier barrier;
class Worker implements Runnable {
public int myRow;
String name;
public CyclicBarrier synchPoint;
Worker(CyclicBarrier barrier, int row, String name) {
myRow = row;
this.name = name;
this.synchPoint = barrier;
this.run();
}
public void run() {
System.out.println("Name: " + name);
processRow(myRow);
mergeRows();
try {
System.out.print("In SynchPoint");
synchPoint.await();
} catch (InterruptedException ex) {
return;
} catch (BrokenBarrierException ex) {
return;
}
}
}
public void processRow(int numRow){
System.out.println("In Process Row");
}
public void mergeRows(){
System.out.println("In merge Row");
}
public Solver(float[][] matrix) {
data = matrix;
N = matrix.length;
System.out.println("N: " + N);
Runnable barrierAction =
new Runnable() { public void run() { mergeRows(); }};
barrier = new CyclicBarrier(N, barrierAction);
List<Thread> threads = new ArrayList<Thread>(N);
for (int i = 0; i < N; i++) {
String myName = "Worker-" + i;
Thread thread = new Thread(new Worker(barrier, i, myName));
threads.add(thread);
thread.start();
System.out.println("In loop, i is: " + i);
}
// wait until done
for (Thread thread : threads)
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void doWork(){
float[][] matrix2 = new float[6][2000];
Solver solve = new Solver(matrix2);
}
public static void main(String[] args) {
Solver.doWork();
}
}
输出:
N:5
姓名:工人-0
在处理行中 行是:0
数据长度:5
在合并行中 在合并行中 在SynchPoint中
答案 0 :(得分:5)
你有一个讨厌的习惯,让你的构造函数除了初始化一个实例之外还能工作。 Solver
的构造函数执行此操作并不是最终有害,但Solver.Worker
调用实例的run()
方法的事实是源你的问题。
您在应用程序的主线程中运行Worker
构造函数。该构造函数调用run()
,它在到达synchPoint.await()
时挂起该线程。当有足够的其他线程到达那个点时,线程将恢复,但是没有一个线程将会恢复,因为所做的一个线程是那个已经创建并启动其他线程的线程,并且它无法继续。
从this.run()
的构造函数中删除Worker
,您应该会进一步了解。