Are you taking CLEP classes? Try clep.ai
| preferred AP College board partner for AP classes
AP Computer Science A/Unit 8: 2D Array
Start Practice TestPractice Test
About Exam
hard

Java Synchronization for Thread Safety

Mark
< Prev
Next >

In the GameBoard class shown below, what is the primary purpose of the synchronized block within the play method?

public class GameBoard {
    private int[][] board = new int[3][3];

    public void play(int row, int col, int player) {
        synchronized(board) {
            if (board[row][col] == 0) {
                board[row][col] = player;
            }
        }
    }

    public void printBoard() {
        for (int[] row : board) {
            for (int cell : row) {
                System.out.print(cell + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        GameBoard game = new GameBoard();
        Thread t1 = new Thread(() -> game.play(1, 1, 1));
        Thread t2 = new Thread(() -> game.play(1, 1, 2));
        t1.start();
        t2.start();
    }
}
A

It automatically makes the printBoard() method thread-safe even when called concurrently.

B

It prevents deadlock by ensuring that only one thread can access the board at once.

C

It ensures that the board is reallocated safely before any updates occur.

D

It prevents two threads from marking the same cell simultaneously, thus avoiding a race condition.

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer
Report Question

Question Leaderboard

Not enough data yet to show leaderboard.

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Privacy Policy|