Java多線程知識點總結——進階篇(十) 之 中斷線程

停止線程運行時有一種特殊情況,就是當線程處於了凍結狀態時,就不會讀取到while循環的標記,那麼線程就不會結束。
如下代碼:

class StopThread implements Runnable
{
    private boolean flag =true;
    public synchronized void run()
    {
        while(flag)
        {
            try {
                wait();
            } catch (InterruptedException e) {
                System.out.println(Thread.currentThread().getName()+".... Exception");
            }
            System.out.println(Thread.currentThread().getName()+"....run");
        }
    }
    public void changeFlag()
    {
        flag = false;
    }
}

class  StopThreadDemo
{
    public static void main(String[] args) 
    {
        StopThread st = new StopThread();

        Thread t1 = new Thread(st);
        Thread t2 = new Thread(st);

        t1.start();
        t2.start();

        int num = 0;

        while(true)
        {
            if(num++ == 60)
            {
                st.changeFlag();
                break;
            }
            System.out.println(Thread.currentThread().getName()+"......."+num);
        }
        System.out.println("over");
    }
}

運行結果如下:
這裏寫圖片描述

發現程序卡住了,主要是開闢的線程都進入到了 wait 狀態。這時會有小夥伴說不是有 notify 嗎,注意,這裏除了主線程,其他線程都進入了 wait 狀態,已經不能執行 notify 了。

所以,java提供了一箇中斷線程的方法:

Thread.interrupt()

樣例代碼如下:

class StopThread implements Runnable
{
    private boolean flag =true;
    public synchronized void run()
    {
        while(flag)
        {
            try {
                wait();
            } catch (InterruptedException e) {
                System.out.println(Thread.currentThread().getName()+".... Exception");
                flag = false; //一般中斷線程後,我們讓線程直接停止運行
            }
            System.out.println(Thread.currentThread().getName()+"....run");
        }
    }
    public void changeFlag()
    {
        flag = false;
    }
}

class  StopThreadDemo
{
    public static void main(String[] args) 
    {
        StopThread st = new StopThread();

        Thread t1 = new Thread(st);
        Thread t2 = new Thread(st);

        t1.start();
        t2.start();

        int num = 0;

        while(true)
        {
            if(num++ == 60)
            {
//              st.changeFlag();
                t1.interrupt(); //中斷線程t1
                t2.interrupt(); //中斷線程t2
                break;
            }
            System.out.println(Thread.currentThread().getName()+"......."+num);
        }
        System.out.println("over");
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章