【问题标题】:cannot stop progress bar on Android using Thread.interrupt无法使用 Thread.interrupt 在 Android 上停止进度条
【发布时间】:2015-11-14 11:45:06
【问题描述】:

我遇到了一个我不明白的小问题。我有一个简单的进度条,但 Thread.interrupt 不会停止线程。我必须破解它一个全局变量。我想知道是否有人可以阻止这个问题。

我试过这个线程,但对我不起作用:

How to stop a thread(progressbar) in android

这里是黑客的代码

    // Start lengthy operation in a background thread
    calcThread = new Thread
    (
        new Runnable()
        {
            public void run()
            {
                Thread current = Thread.currentThread();
                //while (!current.isInterrupted()) // this does not
                while (threadLoop) // this hack works
                {
                    doWork();
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {}

                    // Update the progress bar
                    mHandler.post(new Runnable() {
                        public void run() {
                            mProgress.setProgress(mProgressStatus);
                        }
                    });
                }

                Log.d(TAG, "out of thread loop");
            }
        }
    );

    calcThread.start();

现在我尝试停止线程

public void onClickAbout(View view)
{
    if (view.getId() == R.id.buttonAbout)
    {
        Log.d(TAG, "onButtonPressed");

        calcThread.interrupt(); // This does not work
        threadLoop = false; // this works.

    }
}

为什么我必须破解全局?换句话说,为什么 Thread.interrupt 不停止线程。

谢谢!

【问题讨论】:

  • 你为什么不使用 asyncTask ?

标签: java android multithreading


【解决方案1】:

你为什么不试试下面的

线程背景 = new Thread() { 公共无效运行(){

            try{
                for(int s=0;s<=100;s++)
                {

                    s=s+20;
                    sleep(1000);
                    progressbar.setProgress(s);
                }
            }catch(InterruptedException e){
                e.printStackTrace();
            }finally{
               //do some thing after you finish thread
            }
        }
    };
    background.start(); 

【讨论】:

    【解决方案2】:

    它不起作用,因为您正在捕捉 InterruptedException 并忽略它。抛出异常后线程不再中断。 (见this Q&A。)但是k0sh是对的,你应该使用AsyncTask

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-01
      相关资源
      最近更新 更多