来自http://nkeegamedev.blogspot.jp/2013/05/android-thread.html
找了一些blog,看下来只有这个还行。
程式中時需要使用multithread進行背景作業, 但記得必須在程式結束前中止Thread。
查閱文件會發現不論destroy()方法或stop()方法都已聲明不應用來終止thread,而interrupt()方法也並不是用來終止thread。那麼到底該如何正確在應用程式結束時一併終止所建立的Thread,正確的作法是使用interrupt()方法並配合shared variable控制
boolean RUN_THREAD = true;
...
ocrThread =
new Thread(){
public
void run(){
while (
RUN_THREAD){
//執行緒作業
}
}
};
ocrThread.start();
...
protected
void onDestroy() {
RUN_THREAD =
false;
ocrThread.interrupt();
ocrThread =
null;
}
来自这篇blog讲解也不错http://blog.csdn.net/zhangtengyuan23/article/details/50535813
1、正常关闭:推荐使用业务标志位结束线程的工作流程,待线程工作结束自行关闭,
如下 mWorking 进行控制线程的业务是否继续进行:
- /**
- * start thread running
- */
- public void start() {
- mWorking = true;
- if (mThread != null && mThread.isAlive()) {
- if (DEBUG) {
- LogHelper.i(TAG, "start: thread is alive");
- }
- } else {
- mThread = new Thread(new Runnable() {
- @Override
- public void run() {
- int interval = 1000 / FRAMES;
- while (mWorking) {
- moveCircularly();
- moveToPercent();
- postInvalidate();
- SystemClock.sleep(interval);
- }
- if (DEBUG) {
- LogHelper.i(TAG, "run: thread stopping");
- }
- }
- });
- mThread.start();
- }
- }
- /**
- * stop thread running
- */
- public void stop() {
- if (mWorking) {
- mWorking = false;
- }
- }
2、暴力型(不推荐):一般不使用这种方法关闭线程,Thread.interrupt() 较暴力,虽然进行
- mThread.interrupt();
- mThread = null;
终止了线程,但查看源码我们发现:
interrupt() 使线程接受一个终端请求,接下来的线程操作有线程当前状态决定。
- 线程在 wait(), join() 或 sleep() 状态下,它将被唤醒,并被清除状态,让后会收到一个InterruptedException的 Exception,线程中断 Exception 处理.结束工作。
- 线程 blocked 在I/ O操作时,会接收ClosedByInterruptException。同样的,该信道将被关闭,线程结束工作。
- 线程 blocked在Selector 时会立即中断重置状态 return。此情况下,不接收异常。
- /**
- * start running
- */
- public void start() {
- mWorking = true;
- if (mThread != null && mThread.isAlive()) {
- if (DEBUG) {
- LogHelper.i(TAG, "start: thread is alive");
- }
- } else {
- mThread = new Thread(new Runnable() {
- @Override
- public void run() {
- int interval = 1000 / FRAMES;
- while (mWorking) {
- moveCircularly();
- moveToPercent();
- postInvalidate();
- SystemClock.sleep(interval);
- }
- }
- });
- mThread.start();
- }
- }
- public void stop() {
- if (mWorking) {
- if (mThread != null && mThread.isAlive()) {
- mThread.interrupt();
- mThread = null;
- }
- mWorking = false;
- }
- }
其实,项目中会集成个性化的线程池,保证不开启过多的线程进行多线程操作(硬件层CPU 支持的核心数有限,过多的线程只能更加分割 cpu 时间片,无法达到更好的效果),也会有自己的新线程创建、管理和结束操作。
在工作中我们将Android Thread分两种线程进行管理,即
UI Thread (最多 Thread 数由 cpu 核心数决定)和 Bkg Thread (最大Thread数为1).
- private ThreadPoolExecutor mUiThreadPoolExecutor;
- private ThreadPoolExecutor mBkgThreadPoolExecutor;
- private int getUiInitialThreadPoolSize() {
- int cpuCores = Runtime.getRuntime().availableProcessors();
- return Math.max(2, cpuCores / 2); // at least 2, or (cores/2)
- }
我们只进行 addTask 进行ThreadFactory new adding thread. 而不强行进行 thread 的关闭处理,由线程业务结束自行结束线程。
先写到这里,更多关于线程方面的知识以后可以多多交流。