Exam Permalink:
https://www.jobilize.com/java-certification-questions
Question Permalink:
https://www.jobilize.com/synchronized-method-and-threads-in-java
Question 216 / 297:  What are the possible outputs of running this program once as it is, and second with marking swim() synchronized?
Choose 2
class Swimmer implements Runnable{

String name ;

Swimmer(String name){

this.name = name;

}

public void run() {

new Test().swim(name);

}

}

public class Test {

public void swim(String name) {

System.out.print(name);

System.out.print(name);

}

public static void main(String[] args) {

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

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

}

}

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

When running the program as it is, the two threads are invoking swim() on two different Test objects, which means they are not competing on the same object, therefore the output is undetermined. The output could be in any order of two Tom and two Hanks

When synchronizing the anon-static method method, if two threads competing to execute swim() for the same Test object, the first thread to enter the method will seize the lock of this Test object and will only release it when it finishes executing swim(). That means any other thread has to wait for the lock to be released to be able to enter swim(). But the trick in our program, that each thread is invoking swim() on a different Test object, so actually the two threads are not competing on the same object.

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

Oracle Certified Professional Java Programmer

Author:

Access: Public Instant Grading

Ask
Vanessa Soledad
Start Exam
Jemekia Weeden
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>