• 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

runtime exception with respective to thread program

 
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Testzzz
{
public static void main (String [] args)
{
final Foo f = new Foo();
Thread t = new Thread(new Runnable()
{
public void run()
{
f.doStuff();
}
});
Thread g = new Thread()
{
public void run()
{
f.doStuff();
}
};
t.start();
g.start();
}
}
class Foo
{
int x = 5;
public void doStuff()
{
if (x < 10)
{
// nothing to do
try
{
wait();
}
catch(InterruptedException ex)
{
}
}
else
{
System.out.println("x is " + x++);
if (x >= 10)
{
notify();
}
}
}
}
Hi All,
The above program is giving "runtime exceptions" please anybody provide the solution and explanation for this

thanks in advance
venkat ram simha
 
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You're invoking wait and notify from a non-synchronized block, and the object invoking wait and notify does not hold the lock of object on which you're invoking the methods.

Try this:


Although I have to warn you is not recommended to call wait outside a loop. And this code will probably freeze your terminal.
reply
    Bookmark Topic Watch Topic
  • New Topic