I would like to populate the cells of a nRows * nCols
matrix concurrently with random integers. The runnable here is just a setter that sets a cell of the matrix to a random integer.
public class ConcurrentMatrix {
private int nRows;
private int nCols;
private int[][] matrix = new int[nRows][nCols];
private MyConcurrentMatrixFiller myConcurrentMatrixFiller;
public ConcurrentMatrix(int nRows, int nCols, MyConcurrentMatrixFiller filler) {
this.nRows = nRows;
this.nCols = nCols;
this.matrix = new int[nRows][nCols];
Random r = new Random();
for (int row=0; row<nRows; row++) {
for (int col=0; col<nCols; col++) {
Runnable runnable = new Runnable() {
public void run() {
matrix[row][col] = r.nextInt(100);
}
};
filler.execute(runnable); // non-blocking, just depositing runnable in queue.
}
}
}
}
And the filler
starts the thread pool:
public class MyConcurrentMatrixFiller implements Executor {
BlockingQueue<Runnable> channel = new LinkedBlockingQueue<>();
@Override
public void execute(Runnable command) {
channel.offer(command);
}
public MyConcurrentMatrixFiller(int nthreads) {
for (int i=0; i<nthreads; i++) {
activate();
}
}
private void activate() {
new Thread(() -> {
try {
while (true) { channel.take().run(); }
} catch (InterruptedException e) { }
}).start();
}
public static void main(String[] args) {
MyConcurrentMatrixFiller filler = new MyConcurrentMatrixFiller(10);
ConcurrentMatrix cm = new ConcurrentMatrix(10, 10, filler);
}
}
However, my IDE complains that the row
and col
indeces should be final. But I need every runnable to care about it's own cell, so how can I provide these values to the runnable?