Help coderanch get a
new server
by contributing to the fundraiser
  • 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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.
 
That new kid is a freak. Show him this tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/t/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic