GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why wait for ever? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why wait for ever?" Watch "why wait for ever?" New topic
Author

why wait for ever?

tc king
Greenhorn

Joined: Nov 10, 2006
Posts: 11

the problem is that the thread t is waiting for ever,can someone tell me why?
thanks!
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Hi TC,


try to find out what will happen, if after the line
t.start();
the thread t will not start immediately, and the main thread will first continue.

And check the output.



Yours,
Bu.


all events occur in real time
venkatesh pendharkar
Ranch Hand

Joined: Apr 29, 2006
Posts: 106
I think whats happening here is before thread t start run method, main thread has already got the lock on object "t" as it is accessing synbchronized(t) block .So once main method finishes the execution of this block then thread t will start executing synchronized block on run method. Now when thread t executes wait() method,it remains in wait state forever as notify() method is already executed by the main thread.
If you want to confirm this then you can have sleep() method after the line t.start() & try the output.


t.start();
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
}
synchronized(t)
{
for(int i=0;i<10;i++)
System.out.println("main running");
tc king
Greenhorn

Joined: Nov 10, 2006
Posts: 11
thanks venkatesh and Burkhard,just as venkatesh said.
thank you very much!
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
venkatesh pendharkar coded
Thread.sleep(1000);

Dont't give him 1000, give him only 99.

Threads don't have a trade union.
Bu.
Quintin Stephenson
Ranch Hand

Joined: Nov 16, 2006
Posts: 40
Here's a possible solution. I've moved class MyThread to be an internal class to avoid having to write to class files.

class Test {
public static void main(String[] args)
{

MyThread t=new MyThread();
t.start();
synchronized(t)
{
for(int i=0;i<10;i++)
System.out.println("main running");
t.setOk();
}
}
public static class MyThread extends Thread
{
boolean ok = false;
public void run()
{
synchronized(this)
{
while (ok == false)
{

try
{
System.out.println("wait for main");
sleep(99);
}catch(Exception e)
{}
}
}
for(int i=0;i<10;i++)
System.out.println(Thread.currentThread().getName()+":"+i);
}

public void setOk()
{
ok = true;
}
}
}


If at first you don't succeed, try, try again. If you don't try you have failed.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why wait for ever?