This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why wait for ever?

 
tc king
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

the problem is that the thread t is waiting for ever,can someone tell me why?
thanks!
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
venkatesh pendharkar
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks venkatesh and Burkhard,just as venkatesh said.
thank you very much!
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
}
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic