Reputation: 95
...
Thread showWordThread = new Thread() {
public void run() {
try {
sleep(config.delayTime * 1000);
} catch (Exception e) {
System.out.println(e.toString());
}
this.run();
}
};
showWordThread.run();
}
...
It had run for about 5 minutes before error occured:
Exception in thread "Thread-2" java.lang.StackOverflowError.
Why?
I had tried this:
Thread showWordThread = new Thread(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(config.delayTime * 1000);
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
});
showWordThread.start();
But error still occured.
Upvotes: 1
Views: 4310
Reputation: 1499860
Others have explained that you should use a while
loop instead. You're also trying to call the run
method inside your anonymous class declaration. Additionally, you should call start
, rather than run
- when the new thread has started, it will call run
automatically. I'd actually suggest implementing Runnable
rather than extending Thread
, too. So you want:
Thread showWordThread = new Thread(new Runnable() {
@Override public void run() {
while (someCondition) {
try {
Thread.sleep(config.delayTime * 1000);
// Presumably do something useful here...
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
});
showWordThread.start();
Alternatively, consider using a Timer
or ScheduledExecutorService
.
Upvotes: 4
Reputation: 9505
Your code have infinity recursive, you should change the code to:
Thread showWordThread = new Thread() {
public void run() {
while (true) {
try {
Thread.sleep(config.delayTime * 1000);
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
};
showWordThread.start();
Upvotes: 1
Reputation: 6890
You are calling run
method as recursively. Java holds call information(such as parameters) in stack memory so when you are calling a method recursively and there isn't any end point, stack memory will consumed and StackOverflow
exception throws.
Maybe you want increasing Heap Size
of JVM
but this solution don't solve your problem and StackOverflow
will occurred .
I guess you want run a thread continually. I recommend following code:
Thread showWordThread = new Thread()
{
public void run()
{
try
{
sleep(config.delayTime * 1000);
}
catch (Exception e)
{
System.out.println(e.toString());
}
// this.run(); this snnipet code make error
}
};
showWordThread.run();
}
Upvotes: 2
Reputation: 21902
Don't call run() from within the run() method. That'll definitely produce a stack overflow because you keep reentering the same method with no exit condition. Instead use a while
loop.
Thread showWordThread = new Thread() {
public void run() {
while(condition) {
try {
sleep(config.delayTime * 1000);
} catch (Exception e) {
System.out.println(e.toString());
}
}
};
showWordThread.start();
}
Upvotes: 1
Reputation: 887275
Your function calls itself each time you run it.
That results in a stack overflow.
Upvotes: 0