I'm puzzled by them. Can anybody give me an answer? BTW, welcome the discuss. Q1 1. public class SyncTest{ ****** 2. public static void main(String[] args) { 3. final StringBuffer s1= new StringBuffer(); 4. final StringBuffer s2= new StringBuffer(); 5. new Thread () { 6. public void run() { 7. synchronized(s1) { 8. s1.append("A"); 9. synchronized(s2) { 10. s2.append("B"); 11. System.out.print(s1); 12. System.out.print(s2); 13. } 14. } 15. } 16. }.start(); 17. new Thread() { 18. public void run() { 19. synchronized(s2) { 20. s2.append("C"); 21. synchronized(s1) { 22. s1.append("D"); 23. System.out.print(s2); 24. System.out.print(s1); 25. } 26. } 27. } 28. }.start(); 29. } 30. } Which two statements are true? (Choose Two) A. The program prints "ABBCAD" B. The program prints "CDDACB" C. The program prints "ADCBADBC" D. The output is a non-deterministic point because of a possible deadlock condition E. The output is dependent on the threading model of the system the program is running on Q2 class Happy extends Thread { final StringBuffer sb1 = new StringBuffer(); final StringBuffer sb2 = new StringBuffer(); public static void main(String args[]) { final Happy h=new Happy(); System.out.println(h); new Thread() { public void run(){ System.out.println(this); synchronized(this) { h.sb1.append("A"); h.sb2.append("B"); System.out.println(h.sb1); System.out.println(h.sb2); } } }.start(); new Thread() { public void run() { System.out.println(this); synchronized(this) { h.sb1.append("D"); h.sb2.append("C"); System.out.println(h.sb2); System.out.println(h.sb1); } } }.start(); } } What may be the output of this code ?(Choose two) a) ABBCAD b) ABCBCAD c) CDADACB d) CDDACB e) Output non-deterministic because of the chance of deadlock? f) Output determined due to the underlying platform.
Maulin Vasavada
Ranch Hand
Joined: Nov 04, 2001
Posts: 1865
posted
0
hi, for first prog i would choose last two options because it's certianly possible to have a dead lock in the code and if the deadlock doesn't happen then it can be ans A or B depending upon systems' decision. so i would choose the last option as a second answer. for second code, there is no meaning of synchronization as we have synchronize(this) which synchronizes on 'this' object which is the anonymously created thread. so, any valid output sequence is possible. so i would choose the last option as it we can't be sure about the output. i don't know what to choose as a second choice for the answer as i don't find any other valid answer to this. and btw, there seem some problem in second code as we are printing S.o.p(h) but in the answer option we are not having any option that specifies printing toString() for Happy object 'h' having "classname@reference" format. regards maulin