问题:在开发中遇到关闭一个页面(Activity),里面的线程是否随着关闭?
回答:不会(经过测试)
当在开发中遇到需要在activity关闭的时候关闭线程时:
1.可以在线程的Run方法里面设置标记手动关闭. (使用停止的标记位,那么可以保正在真正停止之前完整的运行完)
2.调用Thread.stop()方法也可以,但是会出问题(使用Thread.stop方法停止线程,不能保证这个线程是否完整的运行完成一次)
测试代码:
package com.example.testthread;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
Thread thread;
// private Handler handler = new Handler(){
// @Override
// public void handleMessage(Message msg) {
// super.handleMessage(msg);
// Log.i("TAG", "handler");
// }
// };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
super.onResume();
thread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <4 ; i++) {
Log.i("TAG", "Thread"+i);
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// handler.sendEmptyMessage(0);
Log.i("TAG", "Thread");
}
});
thread.start();
Log.i("TAG", "onResume");
finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
thread.stop();
Log.i("TAG", "onDestroy");
}
}
回答:不会(经过测试)
当在开发中遇到需要在activity关闭的时候关闭线程时:
1.可以在线程的Run方法里面设置标记手动关闭. (使用停止的标记位,那么可以保正在真正停止之前完整的运行完)
2.调用Thread.stop()方法也可以,但是会出问题(使用Thread.stop方法停止线程,不能保证这个线程是否完整的运行完成一次)
测试代码:
package com.example.testthread;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
Thread thread;
// private Handler handler = new Handler(){
// @Override
// public void handleMessage(Message msg) {
// super.handleMessage(msg);
// Log.i("TAG", "handler");
// }
// };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
super.onResume();
thread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <4 ; i++) {
Log.i("TAG", "Thread"+i);
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// handler.sendEmptyMessage(0);
Log.i("TAG", "Thread");
}
});
thread.start();
Log.i("TAG", "onResume");
finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
thread.stop();
Log.i("TAG", "onDestroy");
}
}