I’ve managed to get my thread running and stopping safely but what I would like to know is what is best for starting another thread? I know that you cannot restart a thread so I have to create a new one.
Here is what i mean:
1) First thread called automatically – acts like a simple counter, created using the ‘implements runnable’ method of threading
2) Have a button which interrupts this thread and stores the last value that that thread interacted before it was interrupted.
3) The next button should call a new thread and use that value as it’s starting point. Below is my first stab at the code:
@Override
public void run()
{
Log.v( TAG,"Runnable" );
if( isRunning )
{
Log.v( TAG,"Runnable -> Inside While Loop" );
counter.setText( " "+i );
setCounter( i );
handler.postDelayed( this, 1000 );
i++;
} else if( !isRunning )
{
if( Thread.currentThread().isAlive() )
{
Thread.currentThread().interrupt();
Log.v( "Current Thread:", ""+Thread.currentThread().toString() );
} else {
// Thread not alive
}
}
}
And the resume thread method:
// Cannot restart a thread - you have to create a new one!
public void resumeThrd()
{
// isRunning = true;
Log.v( "isRunning Value:", "TRUE" );
// Create a new Thread to run
newThrd = new Thread( this );
newThrd.start();
}
So – how should i go about it? Should I revamp my original thread method to allow input and call it in my resume method? Is this safe or would the original thread still be active and creating a new one would just slow things down?
Finally how do i create the new thread properly?
Better is to create different
Runnableand useHandlerto manage all theRunnables. So, the best answer will be to useHandlerto manage your thread.In your case to call the
Runnableagain you need to firehandler.postDelayed(runnable, 1000);and to stop the Runnable on the Button Click callhandler.removeCallbacks(runnable);