可运行、暂停和恢复线程

Runnable, Pause and Resume thread

我的应用程序运行良好,但我无法弄清楚为什么我的 void 运行();当我单击 "home" 按钮时,背景中仍然有 运行s。

我希望我的线程在调用 onResume() 时暂停线程 onPause 并再次启动线程!

不知道我做错了什么!

我的代码:

public class MainActivity extends ActionBarActivity {

Thread thread;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    thread = new Thread(new MyThread());
    thread.start();

}


@Override
protected void onPause() {
    super.onPause();
    this.thread.interrupt();

    Log.d("Method:","OnPause();");



}

@Override
protected void onResume(){
    super.onResume();
    this.thread.run();
    Log.d("Method:","onResume();");

}


@Override
protected void onDestroy(){
    super.onDestroy();
    this.thread.interrupt();
    finish();
    Log.d("Method:","onDestroy();");

}

}

内class:

public class MyThread implements Runnable{

    @Override
    public void run() {

        while(!Thread.currentThread().isInterrupted()){
            if(Thread.currentThread().isInterrupted()){

                break;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.d("Method","void run()");
            //Creates a file with SharedPreferences and make editable
            SharedPreferences preferences = getSharedPreferences("MyPrime", Context.MODE_PRIVATE);
            final SharedPreferences.Editor editor = preferences.edit();

            Random random = new Random();
            BigInteger bigInteger = new BigInteger(10,random);

            //Loads and gets the last int value store in the file
            SharedPreferences preferences1 = getSharedPreferences("MyPrime",Context.MODE_PRIVATE);
            final int numberInFile = preferences1.getInt("MyPrime",0);

            if(bigInteger.isProbablePrime(random.nextInt(500))){
                if(numberInFile < bigInteger.intValue()){
                    editor.putInt("MyPrime",bigInteger.intValue());
                    editor.commit();

                }
            }
        }

    }

}

这是因为您捕获并忽略了中断线程时抛出的 InterruptedException。不要忽略异常!

如果您看一下 the relevant docs,您会发现如果您在等待 sleep 调用时中断线程,则会抛出该异常并且中断状态将为 已清除(即 isInterrupted() 将 return 为假)。你的线程可能大部分时间都花在那个睡眠调用上,所以它很可能在那里被打断。

从 onCreate 中删除代码并使您的 onResume 像这样工作。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
protected void onResume(){
    super.onResume();
    thread = new Thread(new MyThread());
    thread.start();
    Log.d("Method:","onResume();");
}