我到底该如何中断线程? [英] How exactly do I interrupt a thread?

查看:160
本文介绍了我到底该如何中断线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图弄清楚如何中断线程.我知道之前已经有人问过这个问题,但是我不确定我是否正确理解.

I'm trying to figure out exactly how to interrupt a thread. I know this has been asked before but I'm not sure I've understood correctly.

我目前有:

public class Test implements Runnable {
    public void run() {
        int i = 0;
        while(!Thread.currentThread().isInterrupted() && i < 100) {
            System.out.println(i++);
        }
    }
    public static void main(String args[]) {
        Thread x = new Thread(new Test());
        x.start();
        for (int i = 0; i < 100; i++) {
            System.out.println(i+100);
            if (i == 75) {
                x.interrupt();
            }
        }
    }
}

这两个线程的总数都为100.这是一个简单的示例,我知道,但是对我来说,如果我在run方法中做一些更复杂的事情,那么外面的while循环可能不够好.所以我要问的是:

Which has both threads count to 100. It's a simple example, I know but it occurs to me that if I was doing something more complicated in the run method then a while loop on the outside might not be good enough. So what I'm asking is:

例如,如果我在run方法中有50行代码,并且我想在那50行代码中的任何地方中断线程,那么我将不得不加载if s来检查其hasn每行之间没有被打扰吗?就目前我对整个事情的理解而言,情况就是如此……这让我觉得我错过了一些事情.

If I have for example 50 lines of code in the run method and I want to interrupt the thread wherever in those 50 lines of code it is then would I have to have loads of ifs to check it hasn't been interrupted between each line? As far as my understanding of the whole thing at the moment goes, that would be the case...which makes me think I've missed something.

感谢您的帮助:)

推荐答案

您的理解是正确的-interrupt用于合作而不是先发制人.由目标线程决定何时安全中断是安全的,并在那时进行适当的检查.如果线程在阻塞时被中断,则某些阻塞操作将抛出InterruptedException,但除此之外,您可以根据需要检查Thread.interrupted().在大多数算法中,您不会想要允许在任意点处进行中断,而只能在您知道状态保持一致的明确定义的地方进行.

Your understanding is correct - interrupt is intended for co-operative rather than pre-emptive interruption. It is up to the target thread to decide when it is safe to be interrupted, and to make the appropriate checks at that time. Certain blocking operations will throw InterruptedException if the thread is interrupted while blocked, but other than that it's up to you to check Thread.interrupted() as appropriate. In most algorithms you don't want to allow interruption at arbitrary points, but only at well defined places where you know the state will be consistent.

请注意,您应该使用Thread.interrupted()而不是Thread.currentThread().isInterrupted()进行检查,因为前者会在检查中断标志后将其重置.一旦isInterrupted返回true,它将在每次调用时继续返回true,直到重置该标志为止,这可能不是您想要的.

Note that you should make the checks using Thread.interrupted() rather than Thread.currentThread().isInterrupted(), as the former resets the interruption flag after checking it. Once isInterrupted returns true it will continue to return true on every call until the flag is reset, which is probably not what you want.

这篇关于我到底该如何中断线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆