File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Java Thread Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Java Thread Question" Watch "Java Thread Question" New topic

Java Thread Question

Sunil Krishnamuthy

Joined: Feb 24, 2005
Posts: 1

I don't quite understand the following Java Thread question posted at:

My understanding is that the this.notify () method will un-block a thread that is waiting due to a this.wait (). However, this does NOT appear to be the case in the following thread code. Can someone explain?

Consider the following multi-threaded code that users inner-class declarations to create and execute multiple threads. What will be the output of the code?

1: public class test
2: {
3: public static void main (String args[])
4: {
5: final String s="s";
6: final Thread t= new Thread (new Runnable ()
7: {
8: public void run () {
9: try
10: {
11: for (int i=1; i < 5; i++)
12: {
13: synchronized (this)
14: {
15: System.out.print (" " + i);
16: this.wait ();
17: }
18: }
19: } catch (Exception ex) { ex.printStackTrace (); }
20: }
21: });
23: Thread t2 = new Thread (new Runnable ()
24: {
25: public void run () {
26: while (true)
27: {
28: synchronized (this) { this.notify (); }
29: }
30: }
31: });
32: t.start ();
33: t2.start ();
34: }
A) A compilation error will occur
B) 1 2 3 4 will be printed
C) A run-time error will be thrown
D) Nothing will be printed to the output
E) 1 will be printed
[Ans: E]
[ February 24, 2005: Message edited by: Sunil Krishnamuthy ]
Animesh Shrivastava
Ranch Hand

Joined: Jul 19, 2004
Posts: 298
According to your code,
The thread t goes into runnable state and prints "1" before going to WAIT state. After that it starts waiting for the acquisition of its own lock.

The thread t2 then goes into runnable state too, and it calls notify on itself, notifying anyone waiting for the lock of this object i.e. t2
But in ur code no one is waiting for the acquisition of lock of the thread object t2. Instead u have thread t waiting for the acquisition of its own lock.

So after printing 1, nothing is printed. But remember here the code goes on for an infinite loop as u have

Now even if u comment the above line, i mean u have

Even then the code gets stuck as thread t is waiting for the acquistion of its own lock and no one is there to notify it.

Hope u getting my point.
I agree. Here's the link:
subject: Java Thread Question
It's not a secret anymore!