1. 程式人生 > 實用技巧 >執行緒中斷interrupt

執行緒中斷interrupt

public class InterruptThread2 extends Thread{

    public static void main(String[] args) {
        try {
            InterruptThread2 t = new InterruptThread2();
            t.start();
            Thread.sleep(1000);
            t.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    
public void run() { super.run(); for(int i = 0; i <= 800000; i++) {//設定中斷標識,執行緒沒有影響,還會繼續執行。執行緒只有在方法執行完了,才會退出, System.out.println("i=" + i); } } public void run1() { super.run(); for(int i = 0; i <= 200000; i++) { //判斷是否被中斷 if
(Thread.currentThread().isInterrupted()){ //設定中斷標識,執行緒沒有影響,還會繼續執行。這裡要執行緒的方法執行完,執行緒就退出了。 //處理中斷邏輯 for(int j = 0;j < 10 ;j++) { System.out.println("sssss" + j); } break; } System.out
.println("i=" + i); } } }
public class InterruptThread1 extends Thread{

    public static void main(String[] args) {
        try {
            InterruptThread1 t = new InterruptThread1();
            t.start();
            Thread.sleep(1000);
            t.stop();//停止不了執行緒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        super.run();
        for(int i = 0; i <= 800000; i++) {//設定中斷標識,執行緒沒有影響,還會繼續執行。執行緒只有在方法執行完了,才會退出,
            try {
                Thread.currentThread().sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("i=" + i);
        }
    }
}