Oracle
1Z0-851 · Question #55
Given: 1. public class TestFive { 2. private int x; 3. 4. public void foo() { 5. int current = x; 6. x = current + 1; 7. } 8. 9. public void go() { 10. for(int i = 0; i < 5; i++) { 11. new Thread()…
The correct answer is A. move the line 12 print statement into the foo() method D. wrap the code inside the foo() method with a synchronized( this ) block. See the full explanation below for the reasoning.
Question
Given: 1. public class TestFive { 2. private int x; 3. 4. public void foo() { 5. int current = x; 6. x = current + 1; 7. } 8. 9. public void go() { 10. for(int i = 0; i < 5; i++) { 11. new Thread() { 12. public void run() { 13. foo(); 14. System.out.print(x + ", "); 15. } 16. }.start(); 17. } 18. } 19.} Which two changes, taken together, would guarantee the output: 1, 2, 3, 4, 5, ? (Choose two.)
Options
- Amove the line 12 print statement into the foo() method
- Bchange line 7 to public synchronized void go() {
- Cchange the variable declaration on line 2 to private volatile int x;
- Dwrap the code inside the foo() method with a synchronized( this ) block
- Ewrap the for loop code inside the go() method with a synchronized block synchronized(this)
How the community answered
(36 responses)- A83% (30)
- B3% (1)
- C6% (2)
- E8% (3)
Community Discussion
No community discussion yet for this question.