• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

K and B Chapter 9

 
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

class Dudes {
4. static long flag = 0;
5. // insert code here
6. if(flag == 0) flag = id;
7. for(int x = 1; x < 3; x++) {
8. if(flag == id) System.out.print("yo ");
9. else System.out.print("dude ");
10. }
11. }
12. }
13. public class DudesChat implements Runnable {
14. static Dudes d;
15. public static void main(String[] args) {
16. new DudesChat().go();
17. }
18. void go() {
19. d = new Dudes();
20. new Thread(new DudesChat()).start();
21. new Thread(new DudesChat()).start();
22. }
23. public void run() {
24. d.chat(Thread.currentThread().getId());
25. }
26. }



And given these two fragments:
I. synchronized void chat(long id) {
II. void chat(long id) {
When fragment I or fragment II is inserted at line 5, which are true? (Choose all that apply.)
A. An exception is thrown at runtime
B. With fragment I, compilation fails
C. With fragment II, compilation fails
D. With fragment I, the output could be yo dude dude yo
E. With fragment I, the output could be dude dude yo yo
F. With fragment II, the output could be yo dude dude yo

The answer for this is F
could any one explain me the the process how F is obtained
im unable to understand the process
thanks in advance
 
Ranch Hand
Posts: 207
jQuery Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
with synchronized chat method only one thread will be able to invoke this method (on static Dudes object d) at a time. Second thread will get a chance to invoke chat only when first chat call returns.
First chat call sets the static flag equal to thread id and then prints "yo" two times. then second thread invokes chat and prints "dudes" two times, and given the above logic second method call can not be made unless first finishes so output will always be "yo yo dude dude"
 
reply
    Bookmark Topic Watch Topic
  • New Topic