0

我有这个代码:

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() 函数用于停止线程运行的 while 变量的值。当我运行代码并按下按钮时,它不会启动线程。任何想法为什么?

4

1 回答 1

0

background.start()被调用时,isRunning仍然是假的,所以线程被启动(但没有进入while循环)并立即停止。

为保证线程在被调用时进入while循环startThread,可以在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

于 2012-05-14T01:09:25.447 回答