Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 这是去';停止';一根细线是否优雅?_Java_Multithreading - Fatal编程技术网

Java 这是去';停止';一根细线是否优雅?

Java 这是去';停止';一根细线是否优雅?,java,multithreading,Java,Multithreading,与循环内变量的连续检查不同: class Tester { public static void main() { Try t = new Try(); Thread.sleep(10); //wait for 10 milliseconds t.interrupt(); // 'interrupt' i.e stop the thread } } public class Try extends Thread { pub

与循环内变量的连续检查不同:

class Tester {
    public static void main() {
        Try t = new Try();
        Thread.sleep(10); //wait for 10 milliseconds
        t.interrupt(); // 'interrupt' i.e stop the thread
    }
}

public class Try extends Thread {
    public void interrupt() {
        //perform all cleanup code here
        this.stop();
        /*stop() is unsafe .but if we peform all cleanup code above it should be okay ???. since thread is calling stop itself?? */
    }
}

为了以良好的方式执行中断,您应该在被中断的线程内轮询“interrupted()”方法。 请注意,调用interrupt()方法会重置中断标志(在调用interrupt()时设置)

我想底线是,您必须在线程内连续轮询,才能执行优雅的中断。

使用方法而不是线程。stop()。在中断线程中,您可以捕获
InterruptedException
并执行所需的任何清理


已经有人问过类似的问题,您也可以在那里找到代码示例。

您永远不应该在线程上调用.stop(),句号。线程本身执行清理是不够的。由于调用.stop()会立即释放所有监视器,因此其他线程可能会看到共享数据处于不一致的状态,这可能会导致几乎无法跟踪错误。

请编辑文章中的代码,使其可读,并确保在文章正文中问这个问题。我已格式化了您的代码并使其可编译(
try
不是有效的类名…。@assylias-oops谢谢