This week's book giveaway is in the Java in General forum.
We're giving away four copies of Helidon Revealed: A Practical Guide to Oracle’s Microservices Framework and have Michael Redlich on-line!
See this thread for details.
  • 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
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Threads MindQ 41

 
Ranch Hand
Posts: 208
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, the question was:

For what reasons might a thread stop execution?
a) A thread with higher priority began execution.
b) The thread's wait() method was invoked.
c) The thread invoked its yield() method.
d) The thread's pause() method was invoked.
e) The thread's sleep() method was invoked.
I chose a,c,e. I didn't include b because it said thread's wait method when in fact actually wait() method is invoked in the monitor object. But i am getting wrong for this. I am unable to verify the answers for any of MindQ questions.
What is the error?
Thanks in advance,
------------------
Regards,
Shree
 
Ranch Hand
Posts: 4716
9
Scala Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thread like any other class inherits the wait() method from object. answer b is correct. here is a program that demonstrates wait() and notifyAll(). i havent compiled this but i believe it is right.


class Waiter extends Thread {
public synchronized void run() {
try {
Thread notifyThread = new Thread(new Notifier());
notifyThread.start();
wait();
}
catch (InterruptedException ie) {
System.out.println("Interrupted.");
}
System.out.println("Waiter back in control.");
}
}
class Notifies extends Thread {
public synchronized void run() {
System.out.println("Notifier running.");
try {
System.out.println("Going to sleep.");
Thread.sleep(100);
System.out.println("Woke up.");
}
catch (InterruptedException ie) {
System.out.println("Interrupted.");
}
System.out.println("Back to waiter.");
notifyAll();
}
}
public class Waiting {
public static void main(String[] args) {
Thread waitThread = new Thread(new Waiter());
waitThread.start();
}
}

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

Hi Randall
only a small change... typo error !!
Instead of Thread notifyThread = new Thread(new Notifier());
it shud be
Thread notifyThread = new Thread(new Notifies());
One question :
Output comming is :
Notifier Running
Going to Sleep
Woke Up
Back to Waiter !!
My question is after notifyAll() the program HANGS !! I mean it waiting in loop or something like that !!
why is it so...becoz shouldnt it actually bring the waiting thread ( Waiter class) back to running when notifyAll() is invoked in code !!
please explain :
tks,
Ashish
tks,
Ashish
 
Randall Twede
Ranch Hand
Posts: 4716
9
Scala Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks. I didnt write this myself. I think the answer is that thread Notifies never gives up the lock(im not sure though).
from the API:
The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object. The awakened threads will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened threads enjoy no reliable privilege or disadvantage in being the next thread to lock this object.
perhaps thread Notifies should call wait() after calling notifyAll()?
does anyone else know more about this?
 
Ashish Agnihotri
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Oh yeah !
A thing has juz struck me. Should have not wait/notify be called on both the threads exclusively.. !! I guess thats why such behaviour !!
any comments !!
tks,
Ashish
 
Randall Twede
Ranch Hand
Posts: 4716
9
Scala Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i am surprised by the output cause after thread Notifier executes notifyAll() it is done and should exit run and die then thread Waiter should print "Waiter back in control". I should try compiling and running it to see if I get the same result.
well i did indeed get the same results. I hope someone can explain.
[This message has been edited by Randall Twede (edited December 11, 2000).]
 
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Shree, Ashish, Randall ...
I think the code, as written, creates a deadlock.
First, a 'Waiter' thread is created. Then it creates a 'Notifies' thread. Trouble is, 'Waiter' now holds the lock on 'Notifies' ... which is part of the original 'Waiter' thread ... how can it 'notify' itself?
If you change the code to as follows, it compiles and runs as expected:

Apologies for the lame explanation. I'm not sure how to write it out in a proper locking diagram.
Hope that helps.
------------------
Jane
The cure for boredom is curiosity.
There is no cure for curiosity.
-- Dorothy Parker
 
Ashish Agnihotri
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Jane,
juz check this thing out. I have added a few System.out's to your code.
class Waiter extends Thread {
public synchronized void run() {
try {

System.out.println("thread Waiter Starts");
wait();
} catch (InterruptedException ie) {
System.out.println("Interrupted.");
}
System.out.println("Waiter back in control.");
}
}
class Notifies extends Thread {
public synchronized void run() {
System.out.println("Notifier running.");
try {
System.out.println("Going to sleep.");
Thread.sleep(100);
System.out.println("Woke up.");
}catch (InterruptedException ie) {
System.out.println("Interrupted.");
}
System.out.println("Back to waiter.");
notifyAll();
System.out.println("going to awake");
}
}
public class Waiting {
public static void main(String[] args) {
Thread waitThread = new Thread(new Waiter());
waitThread.start();
Thread notifyThread = new Thread(new Notifies());
notifyThread.start();
}
}

AFTER THE CODE IS RUN : it never prints "going to awake" and does not go back to "thread Waiter Starts"...
tks,
Ashish
 
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Hi Jane
After running your code it prints "going to awake" but it does not go back to "thread Waiter starts" and the program HANGS!!!
Please somebody explain to me the use of wait() , notify(), notifyAll(). I am really confused!!!
 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Amit,
As you had a doubt regarding the wait(),notify() and notifyAll() methods thought of just giving you some information about it :
i.)wait() method is basically called to make a currently running thread to give up the monitor and go to sleep for the specified number of milliseconds until some other thread enters the same monitor and calls notify().
ii.)notify() is called to wake up the first thread that called wait() on the same object.
iii.)notifyAll() wakes up all the threads that were in the wait state ,and in such case when all the threads are notified at once you might wonder which thread occupies the monitor and then starts execution.Actually the thread which has the highest priority amongst all the other threads occupies the monitor but again if there are multiple threads of the same priority then its left to the scheduler to decide which thread should run first.
Guyz i hope this is useful to you all and doesnt confuse you more ,if it does then do write back your comments ....

Regards,
Poornima.
 
amit sanghai
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Hi Poornima,
You said that wait() method causes the currently running thread to sleep for some time. Then what is the difference between sleep() and wait()?
 
Poornima Shetty
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Amit,
Sorry for the confusion.What i meant to say was when a wait() method is invoked on a thread the thread stops execution and enters a wait state there by releasing the lock that it had occupied on the monitor.Now this thread which enters a wait state resumes execution only when notify() or notifyAll() is called on it.
In case of sleep() method we put a thread to sleep for specified number of milliseconds...and once the time is over the thread starts execution again
say
Thread.sleep(1000);
.....sorry again..hope i am clear now....
Regards,
Poornima.
 
Ashish Agnihotri
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Hi Jane / Anybody else
The question still remains why ?
pl answer.. getting a bit curious...
tks,
Ashish
 
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Ashish,
Nobody will respond now. Everybody is going to hit the books tonight. So will I. Hopefully someone will post an answer by tomorrow.
Rgds
Sahir
 
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hopefully, this code extension will help clarify the main points. As Poornima pointed out, calling notify() or notifyAll() will allow another ready thread that waited on the same monitor to execute. This is important and explains why the above code doesn't work properly. The above code creates two classes that lock on itself. Waiter calls wait() and becomes blocked. Notifies calles notifyAll() but no other thread is waiting for that lock on the instance of class Notifies. Hence, you never see /"Waiter back in control./" printed and the program never exits.
The code extension below creates a third object by which the two threads will compete for. Well, they don't compete in the pure sense because one notifies the other and the program ends soon after. However, it does correctly illustrate how one thread calls notifyAll() and the other thread executes again.
Please excuse the lame method names.
<PRE>class Waiter extends Thread {
public void run() {
System.out.println("thread Waiter Starts");
LockMe.getInstance().runMe("Waiter");
System.out.println("Waiter back in control.");
}
}
class Notifies extends Thread {
public void run() {
System.out.println("Notifier running.");
try {
System.out.println("Going to sleep.");
Thread.sleep(100);
System.out.println("Woke up.");
}catch (InterruptedException ie) {
System.out.println("Interrupted.");
}
System.out.println("Back to waiter.");
LockMe.getInstance().runMe2();
System.out.println("going to awake");
}
}
class LockMe {
private boolean flag;
private static LockMe me;
public synchronized void runMe( String threadName) {
while (!flag) {
System.out.println(threadName + " running runMe()");
try {
wait();
} catch (InterruptedException e) {
System.out.println("Got Interrupted.");
}
}
flag = false;
}
public synchronized void runMe2() {
flag = true;
notifyAll();
}
public static LockMe getInstance() {
if (me == null) {
me = new LockMe();
}
return me;
}
}

public class Waiting {
public static void main(String[] args) {
Thread waitThread = new Thread(new Waiter());
waitThread.start();
Thread notifyThread = new Thread(new Notifies());
notifyThread.start();
}
}
</PRE>
[This message has been edited by Sam Wong (edited December 12, 2000).]
 
Randall Twede
Ranch Hand
Posts: 4716
9
Scala Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you Sam. It seems so obvious now that you have explained it.
 
Sahir Shah
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Thank you Sam. That was very helpful.

Rgds
Sahir
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,
Sheesh ... that's what I get for trying to think at 11PM EST I didn't notice the code still locked!
Sam thanks for setting everything straigt.

------------------
Jane
The cure for boredom is curiosity.
There is no cure for curiosity.
-- Dorothy Parker
 
Randall Twede
Ranch Hand
Posts: 4716
9
Scala Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I agree Sahir and thank you for your contribution!
 
Won't you please? Please won't you be my neighbor? - Fred Rogers. Tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic