我有这段代码:
package org.example.Threading;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ThreadingActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
private doinback background = new doinback();
Handler handle= new Handler(){
@Override
public void handleMessage(Message msg) {
Log.e("INSIDE HANDLER", "About to stop the thread.");
background.stopThread();
}};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.e("ONCREATE", "BEFORE Thread");
background.start();
Log.e("ONCREATE", "AFTER Thread started");
View button = (Button)findViewById(R.id.button1);
button.setOnClickListener(this);
}
class doinback extends Thread{
private volatile boolean isRunning = false;
public void run() {
while(isRunning){
Log.e("INSIDE THREAD", "about to sleep");
handle.sendMessage(handle.obtainMessage());
}
}
public void stopThread()
{
isRunning = false;
}
public void startThread(){
Log.e("INSIDE StartThread","MAKING isRunning True");
isRunning = true;
}
}
public void onClick(View v) {
background.startThread();
Log.e("INSIDE ONCLICK", "made isRunning true, about to leave");
}
}
我试图理解为什么它不会回到线程,如果有什么我做错了,如果是这样,从线程来回的最佳方法是什么,例如使用stopThread() function我改变while变量的值来阻止线程运行。当我运行代码并按下按钮时,它不会启动该线程。有什么想法吗?
答案 0 :(得分:0)
调用background.start()
时,isRunning
仍为false,因此线程已启动(但未进入while循环)并立即停止。
要确保线程在调用startThread
时进入while循环,您可以将以下代码放在startThread()
方法中:
public void startThread(){
isRunning = true;
start();
}
并且您不会在background.start()
中致电onCreate()
,只需删除该行。
修改强>
如果你想保持一个线程处于活动状态,那么你可以“启动”它并根据需要“停止”它,你可以使用以下代码:
public void run () {
while (isRunning) {
if(!isWorking) {
try { Thread.sleep(10); } catch (InterruptedException ex) { }
continue;
}
//.. do your work here.
}
}
您可以使用isRunning
控制线程的运行状态,使用isWorking
控制工作状态。