簡體   English   中英

Java線程中斷:interrupt()vs stop()

[英]Java Thread interruption: interrupt() vs stop()

在Java中使用線程時遇到問題。 在Java中中斷線程時,interrupt()和stop()之間首選的方法是什么? 又為什么呢?

感謝您的任何答復。

從理論上講,無論您提出問題的方式是什么,線程都不應該通過同步標志自己理解何時終止。

這是通過使用interrupt()方法完成的,但是您應該理解,只有當線程處於等待/睡眠狀態(並且在這種情況下會引發異常)時,此“工作”才能起作用,否則,您必須在內部檢查一下自己線程的run()方法(如果線程是否被中斷isInterrupted() (使用isInterrupted()方法),並在需要時退出。 例如:

public class Test {
    public static void main(String args[]) {
        A a = new A(); //create thread object
        a.start(); //call the run() method in a new/separate thread)
        //do something/wait for the right moment to interrupt the thread
        a.interrupt(); //set a flag indicating you want to interrupt the thread

        //at this point the thread may or may not still running 

    }
}

class A extends Thread {

    @Override
    public void run() { //method executed in a separated thread
        while (!this.isInterrupted()) { //check if someone want to interrupt the thread
            //do something          
        } //at the end of every cycle, check the interrupted flag, if set exit
    }
}

Thread.stop()在Java 8中已被棄用,所以我想說Thread.interrupt()是必經之路。 oracles網站上有很長的解釋。 它還為如何使用線程提供了一個很好的示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM