Exam Permalink:
https://www.jobilize.com/java-certification-questions
Question Permalink:
https://www.jobilize.com/synchronized-non-static-method-in-java
Question 220 / 297:  What is the possible result of compiling and running the following code?
public class Test implements Runnable {

Integer id = 0;

public static void main(String[] args) {

new Thread(new Test()).start();

new Thread(new Test()).start();

}

public void run() {

press(id);

}

synchronized void press(Integer id) {

System.out.print(id.intValue());

System.out.print((++id).intValue());

}

}

A  1010
B  0101
C  0123
D  compilation error
E  an exception is thrown at run time
<< First < Previous Next > Last >>
Explanation:

The two threads are executing on two different instances of Test, which means that the two threads are working on two different instances of variable id.

The result "0123" is not possible, because each thread will start with value "0" for "id"

The result "1010" is not possible because "id" starts with value "0" then incremented to "1"

"0101" is a possible output, which happens the first thread to execute seizes the CPU till it finishes method press()

Another scenario may happen when the the CPU switches between the two threads allowing each to execute one print statement at a time, this will result in the output "0011"

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

Oracle Certified Professional Java Programmer

Author:

Access: Public Instant Grading

Ask
Briana Knowlton
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>