Reputation: 744
I'm trying to run a Thread
class every second. I cant use Runnable
. I tried in the following way, but its throwing StackOverflowException
. Can anyone please let me know a standard method to make a thread class run every second.
public class A extends Thread {
public void run() {
//do my stuff
sleep(1*1000,0);
run();
}
}
Upvotes: 8
Views: 14962
Reputation: 19847
Use Timer
's schedule()
or scheduleAtFixedRate()
(difference between these two) with TimerTask
in the first argument, in which you are overriding the run()
method.
Example:
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
@Override
public void run()
{
// TODO do your thing
}
}, 0, 1000);
Your example causes stack overflow, because it's infinite recursion, you are always calling run()
from run()
.
Upvotes: 18
Reputation: 117675
final ExecutorService es = Executors.newCachedThreadPool();
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new Runnable()
{
@Override
public void run()
{
es.submit(new Runnable()
{
@Override
public void run()
{
// do your work here
}
});
}
}, 0, 1, TimeUnit.SECONDS);
Upvotes: 1
Reputation: 1903
Maybe you want to consider an alternative like ScheduledExecutorService
ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
/*This schedules a runnable task every second*/
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
DoWhateverYouWant();
}
}, 0, 1, TimeUnit.SECONDS);
Upvotes: 3