java 多線程基礎(二)

新建線程

    新建線程很簡單。只要使用new關鍵字建立一個線程對象,而且將它start()起來便可。java

public static void main(String[] args) {
    Thread thread = new Thread();
//  thread.run();
    thread.start();
}

    線程start()後會作什麼這纔是問題關鍵,線程Thread有一個run()方法,star()方法就會新建一個線程並讓這個線程執行run()方法。但要注意:若是放開run()方法去掉start()方法也能夠正常編譯執行,可是卻不能新建一個線程,並且當前線程中調用run()方法,只是做爲一個普通的方法調用。這就是start()和run()方法的區別安全

    上述代碼Thread的run()方法什麼都沒有作線程已啓動立刻就結束了。若是要讓線程作點什麼,就必須重載run()方法,把你要作的事情放進去。ide

public static void main(String[] args) {
    Thread thread = new Thread() {
        @Override
        public void run(){
            System.out.println("HELLO 張三");
        }
    };
    thread.start();
}

    但考慮到java是單繼承,所以咱們也可使用Runnable接口來實現一樣的操做。Runnable它只有一個run()方法。默認的Thread.run()就是直接調用內部的Runnable接口。所以,使用Runnable接口告訴該線程該作什麼,更爲合理。this

public class ThreadTest2 implements Runnable{
    @Override
    public void run() {
        System.out.println("Hello 李四");
    }

    public static void main(String[] args) {
        Thread thread = new Thread(new ThreadTest2());
        thread.start();
    }
}

    上述代碼實現了Runnable接口,並將該實例傳入Thread。這樣避免重載Thread.run,單純使用接口來定義Thread也是最多見的作法。編碼

終止線程

    使用stop方法強行終止線程(這個方法不推薦使用,由於stop和suspend、resume同樣,也可能發生不可預料的結果),由於stop()太過暴力,強行把執行通常的線程終止,可能會引發一些數據不一致的問題。spa

thread.stop();

並不推薦使用這種方法來終止線程。線程

線程中斷

    與線程中斷有三種有關的方法,這三個方法看起來很像,因此可能會引發混淆和誤用,但願注意code

//中斷線程
public void interrupt() {
    if (this != Thread.currentThread())
        checkAccess();

    synchronized (blockerLock) {
    Interruptible b = blocker;
        if (b != null) {
            interrupt0();           
            b.interrupt(this);
            return;
        }
    }
    interrupt0();
}
//判斷是否被中斷
public static boolean interrupted() {return currentThread().isInterrupted(true);}
//判斷是否被中斷,並清除當前中斷狀態
public boolean isInterrupted() {return isInterrupted(false);}

    interrupt,名字看上去很像是終止一個線程的方法,可是我能夠很明確地告訴你們,它不能終止一個正在執行着的線程,它只是修改中斷標誌而已,例以下面一段代碼:對象

public static void main(String[] args) throws InterruptedException {
    Thread t1 = new Thread() {
        @Override
        public void run() {
            while (true) {
                System.out.println("張三");
                Thread.yield();
            }
        }
    };
    t1.start();
    t1.interrupt();
}

    執行這段代碼,你會發現一直有Running在輸出,彷佛執行了 interrupt沒有任何變化。雖然t1進行了中斷,可是在t1中沒有中斷處理的邏輯,所以,即便t1縣城被置上了終端狀態,可是這個中斷不會發生任何做用,若是但願t1在中斷後退出,就必須爲它增長相應的中斷處理代碼。以下所示:繼承

public static void main(String[] args) throws InterruptedException {
    Thread t1 = new Thread() {
        @Override
        public void run() {
            while (true) {
                if (Thread.currentThread().isInterrupted()){
                    System.out.println("已中斷");
                    break;
                }
                System.out.println("張三");
                Thread.yield();
            }
        }
    };
    t1.start();
    t1.interrupt();
}

    總之若是指望終止一個正在運行的線程,則不能使用已通過時的Stop方法,須要自行 編碼實現,如此便可保證原子邏輯不被破壞,代碼邏輯不會出現異常。固然,若是咱們使用的是線程池(好比ThreadPoolExecutor類),那麼能夠經過shutdown方法逐步關閉池中的線 程,它採用的是比較溫和、安全的關閉線程方法,徹底不會產生相似stop方法的弊端。

相關文章
相關標籤/搜索