Java結束線程

前言

       最近年底,項目緊很少寫博客了,現在說說最近碰到的問題,筆者在做分佈式JOB系統的時候,遇到一個比較棘手的問題:停止正在運行的線程。

1. 線程的生命週期

線程停止即Terminated狀態是伴隨run方法的結束而生,也就是run完成後由Thread類來決定線程停止了,銷燬資源釋放空間。

關於線程可以看我的另一篇文章:線程的實現,調度和生命週期,純粹理論。

2. 手工停止

使用標記位法interrupt方法,我們知道有interrupt可以用來中斷線程。

demo

public class StopThread {

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

    private static class DemoThread extends Thread{
        @Override
        public void run() {
            for (int i = 0; i < 1000000; i++) {
                System.out.println("i is " + i);
            }
        }
    }
}

運行,然而並沒用,線程照常執行

看API

/**
     * Interrupts this thread.
     *
     * <p> Unless the current thread is interrupting itself, which is
     * always permitted, the {@link #checkAccess() checkAccess} method
     * of this thread is invoked, which may cause a {@link
     * SecurityException} to be thrown.
     *
     * <p> If this thread is blocked in an invocation of the {@link
     * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
     * Object#wait(long, int) wait(long, int)} methods of the {@link Object}
     * class, or of the {@link #join()}, {@link #join(long)}, {@link
     * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
     * methods of this class, then its interrupt status will be cleared and it
     * will receive an {@link InterruptedException}.
     *
     * <p> If this thread is blocked in an I/O operation upon an {@link
     * java.nio.channels.InterruptibleChannel InterruptibleChannel}
     * then the channel will be closed, the thread's interrupt
     * status will be set, and the thread will receive a {@link
     * java.nio.channels.ClosedByInterruptException}.
     *
     * <p> If this thread is blocked in a {@link java.nio.channels.Selector}
     * then the thread's interrupt status will be set and it will return
     * immediately from the selection operation, possibly with a non-zero
     * value, just as if the selector's {@link
     * java.nio.channels.Selector#wakeup wakeup} method were invoked.
     *
     * <p> If none of the previous conditions hold then this thread's interrupt
     * status will be set. </p>
     *
     * <p> Interrupting a thread that is not alive need not have any effect.
     *
     * @throws  SecurityException
     *          if the current thread cannot modify this thread
     *
     * @revised 6.0
     * @spec JSR-51
     */
    public void interrupt() {
        if (this != Thread.currentThread())
            checkAccess();

        synchronized (blockerLock) {
            Interruptible b = blocker;
            if (b != null) {
                interrupt0();           // Just to set the interrupt flag
                b.interrupt(this);
                return;
            }
        }
        interrupt0();
    }

    private native void interrupt0();

說了半天其實並不是終止線程,只是打了個status狀態,且能被sleep join wait 清除掉,有了標記就好說了,我們可以在程序中判定標識,然後讓線程快速return出棧,來停止線程。同時我們也可以自己通過標記位來提前終止線程。

public class StopThread {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new DemoThread();
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }

    private static class DemoThread extends Thread{
        @Override
        public void run() {
            for (int i = 0; i < 1000000; i++) {
                if (Thread.currentThread().isInterrupted())
                    return;
                System.out.println("i is " + i);
            }
        }
    }
}

可以看到

線程沒運行完成結束了。

下面看看sleep方法的影響

public class StopThread {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new DemoThread();
        thread.start();
//        Thread.sleep(1000);
        thread.interrupt();
    }

    private static class DemoThread extends Thread{
        @Override
        public void run() {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < 1000000; i++) {
                if (Thread.currentThread().isInterrupted())
                    return;
                System.out.println("i is " + i);
            }
        }
    }
}

看結果,標記位被清除了

爲了應對這種情況,我們可以自己打標記位

public class StopThread {

    private static volatile boolean isStopped = false;

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new DemoThread();
        thread.start();
        Thread.sleep(1000);
//        thread.interrupt();
        isStopped = true;
    }

    private static class DemoThread extends Thread{

        @Override
        public void run() {
            for (int i = 0; i < 1000000; i++) {
                if (isStopped)
                    return;
                System.out.println("i is " + i);
            }
        }
    }
}

結果符合預期

注意變量被volatile修飾,方便線程共享。

也可以使用拋異常方式結束線程,可以打印出堆棧信息

3. stop

線程提供stop方法,雖然廢棄了,但迫不得已的時候仍然可以留着備用。

分析一下

/**
     * Forces the thread to stop executing.
     * <p>
     * If there is a security manager installed, its <code>checkAccess</code>
     * method is called with <code>this</code>
     * as its argument. This may result in a
     * <code>SecurityException</code> being raised (in the current thread).
     * <p>
     * If this thread is different from the current thread (that is, the current
     * thread is trying to stop a thread other than itself), the
     * security manager's <code>checkPermission</code> method (with a
     * <code>RuntimePermission("stopThread")</code> argument) is called in
     * addition.
     * Again, this may result in throwing a
     * <code>SecurityException</code> (in the current thread).
     * <p>
     * The thread represented by this thread is forced to stop whatever
     * it is doing abnormally and to throw a newly created
     * <code>ThreadDeath</code> object as an exception.
     * <p>
     * It is permitted to stop a thread that has not yet been started.
     * If the thread is eventually started, it immediately terminates.
     * <p>
     * An application should not normally try to catch
     * <code>ThreadDeath</code> unless it must do some extraordinary
     * cleanup operation (note that the throwing of
     * <code>ThreadDeath</code> causes <code>finally</code> clauses of
     * <code>try</code> statements to be executed before the thread
     * officially dies).  If a <code>catch</code> clause catches a
     * <code>ThreadDeath</code> object, it is important to rethrow the
     * object so that the thread actually dies.
     * <p>
     * The top-level error handler that reacts to otherwise uncaught
     * exceptions does not print out a message or otherwise notify the
     * application if the uncaught exception is an instance of
     * <code>ThreadDeath</code>.
     *
     * @exception  SecurityException  if the current thread cannot
     *               modify this thread.
     * @see        #interrupt()
     * @see        #checkAccess()
     * @see        #run()
     * @see        #start()
     * @see        ThreadDeath
     * @see        ThreadGroup#uncaughtException(Thread,Throwable)
     * @see        SecurityManager#checkAccess(Thread)
     * @see        SecurityManager#checkPermission
     * @deprecated This method is inherently unsafe.  Stopping a thread with
     *       Thread.stop causes it to unlock all of the monitors that it
     *       has locked (as a natural consequence of the unchecked
     *       <code>ThreadDeath</code> exception propagating up the stack).  If
     *       any of the objects previously protected by these monitors were in
     *       an inconsistent state, the damaged objects become visible to
     *       other threads, potentially resulting in arbitrary behavior.  Many
     *       uses of <code>stop</code> should be replaced by code that simply
     *       modifies some variable to indicate that the target thread should
     *       stop running.  The target thread should check this variable
     *       regularly, and return from its run method in an orderly fashion
     *       if the variable indicates that it is to stop running.  If the
     *       target thread waits for long periods (on a condition variable,
     *       for example), the <code>interrupt</code> method should be used to
     *       interrupt the wait.
     *       For more information, see
     *       <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
     *       are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
     */
    @Deprecated
    public final void stop() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            checkAccess();
            if (this != Thread.currentThread()) {
                security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
            }
        }
        // A zero status value corresponds to "NEW", it can't change to
        // not-NEW because we hold the lock.
        if (threadStatus != 0) {
            resume(); // Wake up thread if it was suspended; no-op otherwise
        }

        // The VM can handle all thread states
        stop0(new ThreadDeath());
    }

Stopping a thread with Thread.stop causes it to unlock all of the monitors that it  has locked (as a natural consequence of the unchecked <code>ThreadDeath</code> exception propagating up the stack).

Stopping a thread with Thread.stop causes it to unlock all of the monitors that it  has locked

停止會對monitors造成unlock,造成對資源控制失控,推薦我們對run方法return來提前結束線程,interrupt用來中斷wait

 

總結

       其實線程的停止就是讓線程提前結束,即run方法通過標識提前返回,這是官方推薦的做法。運用線程運行完成自動結束的生命週期來停止線程,stop方法已廢棄,不推薦使用,除非及其特殊的場景。

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章