线程运行中的问题

时间:2011-05-06 11:26:29

标签: android

我用[开始/暂停]和[重置]按钮进行简单的秒表。暂停后按下开始按钮时出现问题。 run方法不是调用。请帮我。 我的代码是

public class StopWatch3 extends Activity implements Runnable{

// text view influenced by the Thread
private TextView threadModifiedText;
int time=0;
Button b1,b2,b3;
boolean shouldRun = false;
/** Called when the activity is first created. */
Thread currentThread = new Thread(this);
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.stopwatch);

    b1=(Button)findViewById(R.id.button1);
    b2=(Button)findViewById(R.id.button2);
    b3=(Button)findViewById(R.id.button3);
    threadModifiedText = (TextView) findViewById(R.id.textView1);
    Log.e("before",""+currentThread.getState());
    b1.setOnClickListener(new View.OnClickListener() 
    {
        public void onClick(View view) 
        {
            Log.e("stopw",(String) b1.getText());
            if(b1.getText().toString().equals("start")){
                    if(currentThread.getState()==Thread.State.NEW){
                        currentThread.start();
                        Log.e("after",""+currentThread.getState());
                        shouldRun = true;
                        b1.setText("pause");
                    }
                    else{
                      shouldRun = true;
                      b1.setText("pause");
                    }
            }
            else if(b1.getText().toString().equals("pause")){
                shouldRun = false;
                b1.setText("start");
            }
        }

    });     
    b2.setOnClickListener(new View.OnClickListener() 
    {
        public void onClick(View view) 
        {
            time=0;
        }

    });               
}


@Override
public void run(){
    try {
        while(shouldRun){
            Thread.sleep(1000);
            threadHandler.sendEmptyMessage(0);
        }
    } catch (InterruptedException e) {
    }   
}


private Handler threadHandler = new Handler() {
    public void handleMessage(android.os.Message msg) {
        time++;
        threadModifiedText.setText(""+time);
    }
};

}

2 个答案:

答案 0 :(得分:1)

你完成它的工作后就无法启动线程,无论如何他的状态不再是新的,你必须在这种情况下创建一个新线程。

当您第二次按“开始”时,您将到达此部分:

else{
    shouldRun = true;
    b1.setText("pause");
}

此代码中的任何内容都不会使线程再次运行...

答案 1 :(得分:0)

我认为当你将shouldRun设置为false时,你的线程就会结束。 将while循环包含在另一个while循环中,只要程序运行,该循环就为真。