• 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

another thread doubt

 
Ranch Hand
Posts: 817
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi i didn't understand the following stuff at all....
its from K&B.. and i read it many times ...
and after reading it 5-6 times ...
didnt clear it fully...

please anybody explain me ....here it goes

=============================================================Let’s take a look at some real code
that shows one object waiting for another object to notify it (take note, it is somewhat
complex):
1. class ThreadA {
2. public static void main(String [] args) {
3. ThreadB b = new ThreadB();
4. b.start();
5.
6. synchronized(b) {
7. try {
8. System.out.println("Waiting for b to complete...");
9. b.wait();
10. } catch (InterruptedException e) {}
11. }
12. System.out.println("Total is: " + b.total);
13. }
14. }
15.
16. class ThreadB extends Thread {
17. int total;
18.
19. public void run() {
20. synchronized(this) {
21. for(int i=0;i<100;i++) {
22. total += i;
23. }
24. notify();
25. }
26. }
27. }
This program contains two objects with threads: ThreadA contains the main thread
and ThreadB has a thread that calculates the sum of all numbers from 0 through 99.
As soon as line 4 calls the start() method, ThreadA will continue with the next
line of code in its own class, which means it could get to line 12 before ThreadB has
finished the calculation. To prevent this, we use the wait() method in line 9.
Notice in line 6 the code synchronizes itself with the object b—this is because in
order to call wait() on the object, ThreadA must own a lock on b. For a thread to
call wait() or notify(), the thread has to be the owner of the lock for that object.
When the thread waits, it temporarily releases the lock for other threads to use, but
it will need it again to continue execution. It is common to find code such as the
following:
synchronized(anotherObject) { // this has the lock on anotherObject
try {
anotherObject.wait();
// the thread releases the lock and waits
// To continue, the thread needs the lock,
// so it may be blocked until it gets it.
} catch(InterruptedException e){}
}
The preceding code waits until notify() is called on anotherObject.
synchronized(this) {
notify();
}
This code notifies any thread currently waiting on the this object.
The lock can be acquired much earlier in the code, such as in the calling method.

==============================================================

i will be gr8full
 
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When wait() is called, the main thread of execution (ThreadA) stops executing and goes into a waiting state. ThreadA gives up its lock on the b object and waits to be notified that it can try to regain the lock on b and continue executing. Since that thread went into a waiting state and gave up its lock on b, the other thread (ThreadB), whose code is synchronized on the b object, can execute. When ThreadB calls notify(), the waiting thread (ThreadA) gets notified that it should stop waiting. ThreadB's synchronized code ends, so it releases its lock on b. ThreadA grabs that lock and resumes executing from where it left off.
[ April 23, 2005: Message edited by: Joe Sanowitz ]
 
amit taneja
Ranch Hand
Posts: 817
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanx joe

so does that means both thread are in synchornization mode using object b so when one ( say Thread A ) goes to waiting other thread takes over it and will start execution till it completes or notifies the first one ( Thread A)
??

One more thing .. is thread lose its lock on object when it goes in waiting state..?
as in Thread A may be doing in above ?

please clear my doubt

thanx
[ April 23, 2005: Message edited by: amit taneja ]
 
Joe Sondow
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

so does that means both thread are in synchornization mode using object b so when one ( say Thread A ) goes to waiting other thread takes over it and will start execution till it completes or notifies the first one ( Thread A)??



You can see that both threads have portions of code that are synchronized because of line 6 and line 20 where the keyword synchronized is used to label a method or block.

Yes, they are both synchronized on the same object. In the context of ThreadA's main method, that object is referenced by a variable named b. In the context of ThreadB's run method, that same object is referenced by the keyword this.

When ThreadA goes into a waiting state, it releases its locks. Any other thread that wants to take the lock on b is free to do so. ThreadB takes the lock so its synchronized block can execute. When notify is called on the this object, ThreadA stops waiting and tries to reclaim the lock on b that it needs in order to continue executing.

Note that notify does not make the lock available. All notify does is tell ThreadA to stop waiting, and to try to reclaim the lock. What makes the lock available is the fact that ThreadB's synchronized block ends. That's when ThreadA succeeds in reclaiming the lock.

One more thing .. is thread lose its lock on object when it goes in waiting state..?
as in Thread A may be doing in above ?



Yes, that's correct.
 
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Joe,

I inserted some comments and ran the code.



I get varied outputs on different runs.

Two of them are as below -
-------------------------
a)

just after b.start
Waiting for b to complete...
inside b.run...
before b.notify
Total is: 4950
Outside b's synchronized block...

b)

inside b.run...
before b.notify
Outside b's synchronized block...
just after b.start
Waiting for b to complete...
-----------------------------------

As soon as b.start() is called from the main thread, we cannot assume that the next line of code in ThreadA will be executed and ThreadA will secure the lock on b and hence go in to wait mode and so on. Am I right ?

Looking at the output of the second execution, I see that the main thread calls b.start() and immediately, run method is executed (can I say "ThreadB secures the lock on b" ? ), right ? The synchronized block completes, notifies and comes out. The main thread gets into synchronized block and goes in to wait mode. And hangs...

Is my understanding of the situation correct ? My question is, how can they assume that ThreadA will wait for ThreadB to finish calculation ?

Thanks,
Soumya.
[ April 24, 2005: Message edited by: soumya ravindranath ]
 
soumya ravindranath
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is anyone interested in replying ?
Thanks,
Soumya
 
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have expected the same result as here we don't have synchronized method just block. So result should be varying. But I have heard everybody saying that after b.start() it will execute next line so in this sense the result is right.

Can somebody clarify that result will be same or varying?

Thanks.
 
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As soon as start() is called the new thread will be created and which thread runs after that depends on the JVM . We cant assume that a particular thread will run or that the output will be same!!

Soumya your understanding of the situation seems to be fine
 
Ranch Hand
Posts: 485
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
so the answer is unpredictable can i say that
 
Jagadesh cs
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i guess you can !!!
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic