Question 217 / 297:  What are the possible outputs of running this program once as it is, and second with marking swimIn() synchronized?
Choose 2
class Swimmer implements Runnable {

String name;

Pool pool;

Swimmer(String name, Pool pool) {

this.name = name;

this.pool = pool;

}

public void run() {

pool.swimIn(name);

}

}

public class Pool {

public void swimIn(String name) {

System.out.print(name);

System.out.print(name);

}

public static void main(String[] args) {

Pool pool = new Pool();

new Thread(new Swimmer("Tom", pool)).start();

new Thread(new Swimmer("Hanks", pool)).start();

}

}

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

When running the program as it is, the two threads are invoking swimIn() on the same Pool object, but since swimIn() is not synchronized, no thread can seize the lock of the object and force the other thread to wait till it completely finishes executing swimIn().

When synchronizing the anon-static swimIn() method, the two threads are competing to execute swim() for the same Pool object, the first thread to enter the method will seize the lock of this Pool object and will only release it when it finishes executing swimIn(). That means any other thread has to wait for the lock to be released to be able to enter swimIn().

Exam Home Page
Ask
Madison Christian
Start Test
Sarah Warren
Start Test
Saylor Foundation
Start Quiz
Edgar Delgado
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>