• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Threads Q

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


What will the above code print?

Select 1 correct option.
a It will keep on printin same values for x and y incrementing by 1 on each line.

b It will keep on printin same values for x and y but they may be incrementing by more than 1 on each line.

c It may print different values for x and y but both the values will be incrementing by 1 on each line.

d You cannot say anything about the values.

Given answer: d
I was expecting a as the o/p, since synchronized keyword is used.
Why is d) the answer?

[ March 13, 2005: Message edited by: Kedar Dravid ]
[ March 13, 2005: Message edited by: Kedar Dravid ]
 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think your 'for' loop is ill-constructed, can you update your code please.
 
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There are two Test objects created. Each thread calls run() synchronized on its own Test object. Not only can x be incremented, then x,y printed by the other thread, then y incremented, but x++ and y++ are not atomic or thread safe so you can get almost any result.
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Answer a would have been ok if the code was looking like this:



Here the incrementation of x and y is synchronized by the call to the static method. The lock is the same for each Test instance, unlike in the original piece of code.

Another solution :

[ March 13, 2005: Message edited by: Ipfa Ov ]
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic