Jea*_*rre 0 java multithreading
我想使用多个线程处理数据,但目前只有第一个线程运行,然后它完全停止.
我正在尝试打印出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();
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
N:5
名称:
Process -0 在Process Row
Row中:0
数据长度:5
在合并行中
合并行在
SynchPoint中
你有一个讨厌的习惯,让你的构造函数除了初始化一个实例之外还能工作.Solver
构造函数执行此操作并不是最终有害的,但Solver.Worker
调用实例run()
方法的事实是您的问题的根源.
您Worker
在应用程序的主线程中运行构造函数.该构造函数调用run()
,它在到达时挂起该线程synchPoint.await()
.当足够的其他线程到达该点时,线程将恢复,但是没有一个线程将会恢复,因为所做的一个线程是创建并启动其他线程的线程,并且它无法继续.
删除this.run()
from Worker
的构造函数,你应该得到更多.
归档时间: |
|
查看次数: |
37 次 |
最近记录: |