Win a copy of TDD for a Shopping Website LiveProject this week in the Testing forum!
  • 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Synchronized Question?

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

I am expecting the t1.start() Thread work first. But the output show's t1.restart(); calls first. Pls let me know why the t1.start() is not calling first.

Thanks, Raghu.K

class TestThread extends Thread{
public void restart()
{
startMe();
}
public void startMe()
{
synchronized(this)
{
notifyAll();
System.out.println("Trying to notify");
}
}
public void run() {
try
{
synchronized(this)
{
wait();
System.out.println("Notify");
}
}
catch(InterruptedException e)
{}
}
public static void main(String[] args) {
TestThread t1 = new TestThread();
t1.start();
t1.restart();
}
 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Ragu

When calling start() on your new thread it will only put it into a runnable state and it's then up to the thread scheduler when it will be run.

The restart() method of your thread (t1) is called by the main thread which most likely will get there before your thread (t1) moves into a running state.
So, when notifyAll() is called from the main thread there are no threads waiting and therefore it will sit "Trying to notify" since it also has the lock on the object.

Basically, t1 will never get the lock of the object as the main thread has it and won't let go until another thread picks up.

If you insert t1.yield() in between start and restart it may give the new thread t1 a chance to run.

t1.start();
t1.yield();
t1.restart();
 
RAGU KANNAN
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You are awesome Peter.
 
How do they get the deer to cross at the signs? Or to read this tiny ad?
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic