为什么这个线程不会暂停和循环?

时间:2012-03-23 22:21:36

标签: android multithreading loops

一旦用户按下buttonStart,我需要这个线程缓慢循环并暂停integerTime的持续时间。说到Android,我是一个业余爱好者,我花了大约12个小时试图让它发挥作用。如果有人可以帮助或纠正我的代码,我将非常感激。干杯。

 final Button button = (Button) findViewById(R.id.buttonStart);             // Making the button to launch the
    button.setOnClickListener(new View.OnClickListener() {                     // actions below
        public void onClick(View v) {

            editTextTarget = (EditText)findViewById(R.id.editTextTarget);      // After user presses 'Start', it will
            stringTarget = editTextTarget.getText().toString();               // convert the input 'Target' into a string

            editTextPayload = (EditText)findViewById(R.id.editTextPayload);    // After user presses 'Start', it will
            stringPayload = editTextPayload.getText().toString();             // convert the input 'Payload' into a string and
            integerPayload = Integer.parseInt(stringPayload);                // then convert the string into an integer

            editTextTime =(EditText)findViewById(R.id.editTextTime);        // After user presses 'Start', it will
            stringTime = editTextTime.getText().toString();                // convert the input 'Time' into a string and
            integerTime = Integer.parseInt(stringTime);                   // then convert the string into an integer

            Thread threadBegin = new Thread()
            {
            public void run(){
                while (DOSrunning.get()) {
                try {
                    Thread.sleep(integerTime);               
                } catch (ClientProtocolException e) {
                } catch (IOException e) {
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                }
                    }
            ;};

            threadBegin.start();

1 个答案:

答案 0 :(得分:1)

你的代码看起来很好。您正在创建一个扩展Thread的匿名类,覆盖run()方法。你需要在@Override之前有一个run(),我很困惑为什么你需要以下捕获量,除非你切掉一些内循环。

} catch (ClientProtocolException e) {
} catch (IOException e) {

我也看不出DOSrunning()是如何设置的。它看起来像AtomicBoolean,这很好。你确定它被初始化为true吗?

 AtomicBoolean DOSrunning = new AtomicBoolean(true);

如果不是那么问题必须是intergerTime中的值不是毫秒。值1000将睡眠1秒。

最后,请务必正确处理InterruptedException。像这样的东西是更好的模式:

} catch (InterruptedException e) {
    // reset the interrupted flag
    Thread.currentThread().interrupt();
    e.printStackTrace();
    // quit the thread if necessary
    return;
}
相关问题