Exam Permalink:
https://www.jobilize.com/java-certification-questions
Question Permalink:
https://www.jobilize.com/synchronizing-and-mutlithreading-in-java
Question 228 / 297:  The idea of this program is to allow two workers to build a wall (which consists of bricks and cement) , given the following code, what necessarily modifications are needed to build a wall by alternating between bricks and cement (brickcementbrickcement...) and to avoid as possible, one worker monopolizing the work alone ? (choose all what apply)
Choose 2
class Worker extends Thread {

Contract contract;

Worker(Contract contract) {

this.contract = contract;

}

public void run() {

contract.work();

}

}

public class Contract {

StringBuilder wall = new StringBuilder("brick");

boolean isCementLastAdded = false;

public void putBrick() {

if (isCementLastAdded ;; !isWallDone()) {

wall.append("brick");

isCementLastAdded = false;

}

}

public void putCementLayer() {

if (!isCementLastAdded ;; !isWallDone()) {

wall.append("cement");

isCementLastAdded = true;

}

}

public boolean isWallDone() {

return wall.length() >= 100;

}

public void work() {

while (!isWallDone()) {

putCementLayer();

putBrick();

}

}

public static void main(String[] args) {

Contract contract = new Contract();

new Worker(contract).start();

new Worker(contract).start();

}

}

<< First < Previous Next > Last >>
Explanation:

What is needed is to synchronize putBrik() and putCementLayer(), where in these methods, the shared variables wall and isCementLastAdded are being modified and by synchronizing we avoid conflict reading/writing to these variable.

Synchronizing work() is a big mistake, by doing so, you are allowing only one worker to monopolize the work. It is a good thing for the other worker since he/she won't work but still be paid :) but we need to be fair :)

Thread.sleep() has no attribute in solving the problem

Exam Home Page
https://www.jobilize.com/java-certification-questions

Oracle Certified Professional Java Programmer

Author:

Access: Public Instant Grading

Ask
Sean WiffleBoy
Start Quiz
Danielle Stephens
Start Quiz
Savannah Parrish
Start Exam
Dravida Mahadeo-J...
Start Quiz
Copy and paste the following HTML code into your website or blog.
<iframe src="https://www.jobilize.com/embed/java-certification-questions" width="600" height="600" frameborder="0" marginwidth="0" marginheight="0" scrolling="yes" style="border:1px solid #CCC; border-width:1px 1px 0; margin-bottom:5px" allowfullscreen webkitallowfullscreen mozallowfullscreen> </iframe>