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();
}
}
We can use a Handler to run code on a given thread after a delay or repeat tasks periodically on a thread. This is done by constructing a Handler and then "posting" Runnable code to the event message queue on the thread to be processed.
Developers multithread Android applications in order to improve their performance and usability. By spinning off processor- or resource-intensive tasks into their own threads, the rest of the program can continue to operate while these processor intensive tasks finish working.
By using join you can ensure running of a thread one after another.
A core (CPU) in Processor will handle only one Task ( Process or Thread ) at a given time. so in Processor with 1 core will handle one thread at a time. so technically no matter how many threads you open for this processor it will serve a thread at a given time.
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()
.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With