我有一个帖子。该线程从服务器加载数据并将其设置在列表视图中。
点击重启按钮后,我想取消或停止线程然后重启此线程。
我已使用while(true)
并使用interrupt
主题并使用stop()
,但无效!
答案 0 :(得分:1)
如果在/
之前启动了线程,则无法重新启动线程抛出IllegalThreadStateException要停止或启动线程,请使用以下代码
import android.util.Log;
public class ThreadingEx implements Runnable {
private Thread backgroundThread;
private static final String TAG = ThreadingEx.class.getName();
public void start() {
if( backgroundThread == null ) {
backgroundThread = new Thread( this );
backgroundThread.start();
}
}
public void stop() {
if( backgroundThread != null ) {
backgroundThread.interrupt();
}
}
public void run() {
try {
Log.i(TAG,"Starting.");
while( !backgroundThread.interrupted() ) {
//To Do
}
Log.i(TAG,"Stopping.");
} catch( Exception ex ) {
Log.i(TAG,"Exception."+ex);
} finally {
backgroundThread = null;
}
}
}
答案 1 :(得分:0)
public class MyActivity extends Activity {
private Thread mThread;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mThread = new Thread(){
@Override
public void run(){
// Perform thread commands...
for (int i=0; i < 5000; i++)
{
// do something...
}
// Call the stopThread() method.
stopThread(this);
}
};
// Start the thread.
mThread.start();
}
private synchronized void stopThread(Thread theThread)
{
if (theThread != null)
{
theThread = null;
}
}
}
答案 2 :(得分:0)
您可以使用字段告诉您的线程停止,重新启动或取消。
class TheThread extends Thread {
private boolean running = true;
public void run() {
// do this...
// do that...
// .......
if (!running) return;
//Continue your job
}
}