Just when I thought I understood threads, I came across these practice questions, and did not understand the given answer. What would YOUR answer be and why?
QUESTION #1
----------------
5. public class Lockdown implements Runnable {
6. public static void main(
String[] args) {
7. new
Thread(new Lockdown()).start();
8. new Thread(new Lockdown()).start();
9. }
10. public void run() { locked(Thread.currentThread().getId()); }
11. synchronized void locked(long id) {
12. System.out.print(id + "a ");
13. System.out.print(id + "b ");
14. }
15. }
What is true about possible sets of output from this code?
A. Set 6a 7a 7b 8a and set 7a 7b 8a 8b are both possible.
B. Set 7a 7b 8a 8b and set 6a 7a 6b 7b are both possible.
C. It could be set 7a 7b 8a 8b but set 6a 7a 6b 7b is NOT possible.
D. It could be set 7a 8a 7b 8b but set 6a 6b 7a 7b is NOT possible.
QUESTION #2
----------------
5. class NoGo implements Runnable {
6. private static int i;
7. public synchronized void run() {
8. if (i%10 != 0) { i++; }
9. for(int x=0; x<10; x++, i++)
10. { if (x == 4) Thread.yield(); }
11. }
12. public static void main(String [] args) {
13. NoGo n = new NoGo();
14. for(int x=0; x<101; x++) {
15. new Thread(n).start();
16. System.out.print(i + " ");
17. } } }
Which is true?
A. The output can never contain the value 10.
B. The output can never contain the value 30.
C. The output can never contain the value 297.
D. The output can never contain the value 820.
E. Making the run method un-synchronized will NOT change the possible output.