Android線程管理之Thread使用總結

今天先來總結一下Thread使用

Thead生命週期的幾個狀態

New
一旦被實例化之後就處於new狀態

Runnable
調用了start函數之後就處於Runnable狀態

Running
線程被cpu執行 調用run函數之後 就處於Running狀態

Blocked
調用join()、sleep()、wait()使線程處於Blocked狀態

Dead
線程的run()方法運行完畢或被中斷或被異常退出,線程將會到達Dead狀態

Thread主要函數

run() :線程運行時所執行的代碼

start() :用於啓動線程

sleep() : sleep(long millis)//線程休眠,交出CPU,讓CPU去執行其他的任務,然後線程進入阻塞狀態,sleep方法不會釋放鎖

yield() :使當前線程交出CPU,讓CPU去執行其他的任務,但不會是線程進入阻塞狀態,而是重置爲就緒狀態,yield方法不會釋放鎖

join() :join(long millis)等待線程終止,直白的說 就是發起該子線程的線程 只有等待該子線程運行結束才能繼續往下運行

wait() :交出cpu,讓CPU去執行其他的任務,讓線程進入阻塞狀態,同時也會釋放鎖

interrupt() :中斷線程,自stop函數過時之後,我們通過interrupt方法和isInterrupted()方法來停止正在運行的線程,注意只能中斷已經處於阻塞的線程

getId() : 獲取當前線程的ID

getName()/setName() :獲取和設置線程的名字

getPriority()/setPriority() :獲取和這是線程的優先級 一般property用1-10的整數表示,默認優先級是5,優先級最高是10,優先級高的線程被執行的機率高

currentThread() :靜態函數獲取當前線程

實現Thread兩種方式

第一種:繼承Thread類

public static void main(String args[]){
        countThread = new CountThread("count thread");
        countThread.start();
    }
public static class CountThread extends Thread{
        public CountThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            System.out.println(TAG + ":" + Thread.currentThread().getName());
        }
    }

第二種 :實現Runnable接口

 public static void main(String args[]){
        threadMe = new Thread(new CountRunnable());
        threadMe.start();
    }
public static class CountRunnable implements Runnable{

        @Override
        public void run() {
            System.out.println(TAG + ":" + Thread.currentThread().getName());
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章