android線程停止
❶ 如何實現Android 中斷線程的處理
可以用interrupt()方法中斷線程,而線程是否已經中斷則用Thread.currentThread().isInterrupted()方法返回true/false判斷:
1、線程start()後馬上調用interrupt(),在進入run()時中斷標志已經被set on;
2、在處理sleep()可能拋出的InterruptedException時,再次中斷線程即可成功中斷;
3、注意interrupt()方法是set on 中斷標志的,interrupted()方法是判斷後並清除中斷標志的。
public class ThreadDemo extends Thread{
public static void main(String[] args){
try{
ThreadDemo thread = new ThreadDemo();
thread.start();
thread.sleep(100);
thread.interrupt(); //中斷線程
thread.sleep(100);
thread.printStr();
thread.interrupt(); //第三次中斷線程
thread.printStr();
thread.join();
}catch(InterruptedException e){
e.printStackTrace();
}
}
private void printStr(){
System.out.println("thread obj");
}
@Override
public void run() {
while(!Thread.currentThread().isInterrupted()) {
System.out.println("thread running");
try {
Thread.sleep(100);
}catch(InterruptedException e)
{
System.out.println("InterruptedException");
Thread.currentThread().interrupt(); //再次中斷線程
}
}
System.out.println("thread interrupted");
}
}
運行結果:
thread running
InterruptedException
thread interrupted
thread obj
thread obj
❷ Android如何停止線程的方式
一種是調用它裡面的stop()方法,另一種就是你自己設置一個停止線程的標記
(推薦這種)
如果使用Thread.stop方法停止線程,不能保證這個線程是否完整的運行完成一次
run方法;但是如果使用停止的標記位,那麼可以保正在真正停止之前完整的運行完
成一次run方法;第二中方式,但是對於麻煩的動作,解決方式是這一個全局變數,每個復雜的動作都進行判斷一下
❸ android需要考慮結束線程嗎
Android終止線程的方法前提
線程對象屬於一次性消耗品,一般線程執行完run方法之後,線程就正常結束了,線程結束之後就報廢了,不能再次start,只能新建一個線程對象。但有時run方法是永遠不會結束的。
三種方法可以結束線程:
使用退出標志,使線程正常退出,也就是當run方法完成後線程終止。
使用interrupt()方法中斷線程。
使用stop方法強行終止線程(不推薦使用,可能發生不可預料的結果)。
使用退出標志終止線程
使用一個變數來控制循環,例如最直接的方法就是設一個boolean類型的標志,並通過設置這個標志為true或false來控制while循環是否退出。代碼如下:
使用stop方法終止線程
程序中可以直接使用thread.stop()來強行終止線程,但是stop方法是很危險的,就象突然關閉計算機電源,而不是按正常程序關機一樣,可能會產生不可預料的結果,不安全主要是:thread.stop()調用之後,創建子線程的線程就會拋出ThreadDeatherror的錯誤,並且會釋放子線程所持有的所有鎖。
其他注意事項:
前兩種方法都可以實現線程的正常退出,也就是要談的優雅結束線程,第3種方法相當於電腦斷電關機一樣,是不安全的方法。
❹ android viewmodel取消線程
在Activity開啟的子線程並不會自動隨Activity的destroy而關閉,所以必須手動去關閉子線程或者通過boolean的方式讓子線程結束運行。開啟的子線程有for循環的要更加註意。
1 package com.lsw;
2
3 import android.app.Activity;
4 import android.os.Bundle;
5 import android.os.Handler;
6 import android.os.Message;
7 import android.util.Log;
8 public class ThreadDemoActivity extends Activity {
9 private static final String TAG = "ThreadDemo";
10 private int count = 0;
11 private Handler mHandler = new MyHandler();
12 boolean stopThread=false;
13
14 private Runnable mRunnable = new Runnable() {
15
16 public void run() {
17
18 while (!stopThread)
19 {
20 count++;
21 try
22 {
23 Thread.sleep(2000);
24 }
25 catch (InterruptedException e)
26 {
27 // TODO Auto-generated catch block
28 e.printStackTrace();
29 }
30
31 //雖然Message的構造函數是public的,但是最好是使用Message.obtain( )或Handler.obtainMessage( )函數來獲取Message對象,因為Message的實現中包含了回收再利用的機制,可以提供效率。
32 Message message=mHandler.obtainMessage();
33 message.what=0;
34 message.obj=count;
35 mHandler.sendMessage(message);
36 }
37 }
38 };
39
40 @Override
41 public void onCreate(Bundle savedInstanceState) {
42 super.onCreate(savedInstanceState);
43 setContentView(R.layout.main);
44 //開啟子線程
45 new Thread(mRunnable).start();
46 }
47
48 protected void onDestroy() {
49 System.out.println("-----------onDestroy------");
50 stopThread=true;
51 super.onDestroy();
52 };
53
54 class MyHandler extends Handler{
55
56 @Override
57 public void handleMessage(Message msg)
58 {
59 // TODO Auto-generated method stub
60 Log.e(TAG, Thread.currentThread().getName() + " " +msg.obj);
61 setTitle("" +msg.obj);
62 }
63 }
64
65 }
❺ android怎麼停止子線程
一種是調用它裡面的stop()方法,另一種就是你自己設置一個停止線程的標記 (推薦這種)
如果使用Thread.stop方法停止線程,不能保證這個線程是否完整的運行完成一次
run方法;但是如果使用停止的標記位,那麼可以保正在真正停止之前完整的運行完
成一次run方法;第二中方式,但是對於麻煩的動作,解決方式是這一個全局變數,每個復雜的動作都進行判斷一下
❻ 如何終止 android線程池中的任務
終止android線程池中的任務的方法
1.實現Callable介面
2.調用pool.submit()方法,返回futrue對象
3.用future對象來獲取線程的狀態。
java">voidtest(){
ExecutorServicepool=Executors.newFixedThreadPool(2);
Callable<String>s=newCallable<String>(){
@Override
publicStringcall()throwsException{
System.out.println("test");
return"true";
}
};
Future<String>f=pool.submit(s);
System.out.println(f.isCancelled());
System.out.println(f.isDone());
f.cancel(true);
}
❼ android thread 後台線程 怎麼設置隨著主線程的結束而結束
關於線程的結束有以下幾點:
1.不要手動調用stop方法強行終止一個線程,這種方式不安全。
通過幫助文檔,我們可以知道,Android的線程類本身就提供了一些公共方法去結束線程。
final void stop()
This method is deprecated. because stopping a thread in this manner is unsafe and can leave your application and the VM in an unpredictable state
但是,通過說明我們可以看到,這些方法Android本身都是不推薦使用的,通過這種方式結束線程是不安全的。
2.線程里run函數短,執行完後線程會自行銷毀,不用手動去終止。
3.手動停止,通過在run里設置標志先停止運行,再調用Thread.interrupt();注意,在run沒有停止時調用.interrupt()沒有效果。
❽ 如何中斷Android線程
當你在後台使用Thread或者AsyncTask來處理一些耗時的操作時,可能想要對這些線程加以控制,其中包括中斷線程。 很多情況下,當用戶啟動程序的時候,一個後台運行的線程會同時啟動去載入內容。但是,當用戶離開程序時,線程應該被打斷,因為現在用戶已經不再關注程序了,同時也不再關注線程處理的結果,而線程是要佔用系統的資源的,如果不及時中斷線程,會導致系統資源的浪費。 除此之外,你可以使用 Thread.interrupt()或者AsyncTask.cancel() 方法,但是這不會馬上中斷線程,因此,只能在自己的線程中實現中斷並退出。 在許多情況下,後台運行的線程都有一個主循環,因此你可以在循環中判斷線程是否被中斷,若被中斷,則退出循環,從而結束進程。例如一個線程下載線程,可以通過 isInterrupted() 方法判斷當前線程是否被中斷。 thread=newThread(){publicvoidrun(){while(!isInterrupted()&&hasMoreDataToDownload()){ downloadAndWriteSomeMore();}if(isInterrupted()){ ();}else{callBack();}}}thread.start(); thread.interrupt(); 如果線程被中斷,則調用 () 函數,刪除沒有完成下載的文件。當線程沒有被中斷,則調用callBack()函數,可以使用handler發送下載完成的信息。 如果你的線程中沒有這樣一個主循環,例如只是執行一個很耗時的SQL查詢操作,可以在查詢操作之後調用 來判斷是否需要結束線程。