wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Can someone explain the output of this program? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Can someone explain the output of this program?" Watch "Can someone explain the output of this program?" New topic
Author

Can someone explain the output of this program?

hmehta
Greenhorn

Joined: Aug 30, 2000
Posts: 20
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

Joined: Oct 04, 2000
Posts: 73
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

Joined: Aug 30, 2000
Posts: 20
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

Joined: Nov 02, 2000
Posts: 65
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

Joined: Mar 17, 2000
Posts: 5782
'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

Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
 
 
subject: Can someone explain the output of this program?
 
Similar Threads
Join method
Threads confusing
call of thread
notify()
Thead!!!