Java Thread Race Condition
The main method in the MatrixModifier class starts a new thread to execute the run method and concurrently calls the printMatrix method. What is the primary synchronization issue that arises from this design?
public class MatrixModifier implements Runnable {
private int[][] matrix = { {0,0,0}, {0,0,0}, {0,0,0} };
public void run() {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = matrix[i][j] + 1;
try {
Thread.sleep(10);
} catch (InterruptedException e) {}
}
}
}
public void printMatrix() {
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
}
System.out.println();
}
public static void main(String[] args) {
MatrixModifier mod = new MatrixModifier();
Thread modifier = new Thread(mod);
modifier.start();
mod.printMatrix();
}
}
A
Race condition causing printMatrix to read inconsistent or partially updated values.
B
An infinite loop resulting from unsynchronized sleep intervals in run().
C
Deadlock because printMatrix waits indefinitely for run() to finish.
D
Thread starvation due to lower priority of the printMatrix method.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE