This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can someone explain the output of this program?

 
hmehta
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this program has been taken from the Khalid Mughal book and is onn threads. I am able to comprehend the output of this program.
import java.awt.*;
import java.util.*;
class counter implements Runnable
{
private int currentValue;
private Thread worker;
public counter(String threadName)
{
currentValue=0;
worker=new Thread(this,threadName);
System.out.println(worker);
worker.start();
}
public void run()
{
try
{
while(currentValue<5)
{
System.out.println(worker.getName()+":"+(currentValue++));
Thread.sleep(5);
}
}
catch(InterruptedException e)
{
System.out.println(worker.getName()+"interrupted.");
}
System.out.println("Exit from"+worker.getName()+".");
}
public int getValue()
{
return getValue();
}
}
import java.*;
import java.util.*;
public class client
{
public static void main(String args[])
{
counter counterA=new counter("Counter A");//Creating the thread
try
{
int val;
do
{
val=counterA.getValue();
System.out.println("Main thread:"+val);
Thread.sleep(1000);
}while(val<5);
}
catch(InterruptedException e)
{
System.out.println("Main thread interccepted");
}
System.out.println("Exit from the main thread");
}
}
 
Bin Zhao
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Your code will produce Exception in thread "main" java.lang.StackOverflowErrorCounter.
I think your getValue() method should be like:
public int getValue()
{
return currentValue;
}
 
hmehta
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No it doesn't produce any exception try it yourse;f I have tried it but it give a result IU cannot explain...
 
Oliver Grass
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Hmehta,
Bin is right. This code will produce a java.lang.StackOverflowError. At least when running it under NT with jdk1.3....
If you look at your code, you produce an infinite loop by calling getValue() again and again....
cheers
Oliver
[This message has been edited by Oliver Grass (edited November 16, 2000).]
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
'hmehta',
PROPER NAMES ARE NOW REQUIRED!!
Please Read the JavaRanch naming policy for more details.
Javaranch appreciates your cooperation to comply with the official naming policy.
Ajith
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic