代码之家  ›  专栏  ›  技术社区  ›  Joerg S

Java线程中断对我不起作用(在groovy中)

  •  2
  • Joerg S  · 技术社区  · 8 年前

    不知何故,下面的代码不会在线程“name”中设置“interrupted”标志。使循环一直运行到结束。

    发现了很多其他问题 Thread.currentThread().isInterrupted() 已丢失。但事实并非如此:

    def t = Thread.start('name') {
        try {
            for (int i = 0; i < 10 && !Thread.currentThread().isInterrupted(); ++i) {
                println "$i"
                sleep 1000
            }
        } catch (InterruptedException e) {
            println "Catched exception"
            Thread.currentThread().interrupt();
        }
    }
    println "Interrupting thread in 1..."
    sleep 1000
    println "Interrupting thread..."
    t.interrupt()
    sleep 2000
    

    Interrupting thread in 1...
    0
    Interrupting thread...
    1
    2
    3
    4
    5
    6
    7
    8
    9
    

    也尝试使用 ExecutorService cancel(true) 关于回归的未来。也不起作用。

    2 回复  |  直到 8 年前
        1
  •  4
  •   aventurin    8 年前

    如果您在 sleep ing,睡眠中断线程 catches 这个 InterruptedException Thread.sleep 中断状态被清除。所以你的 Thread.currentThread().isInterrupted() 始终返回 false

    如果替换 sleep 1000 具有 Thread.sleep(1000) .

        2
  •  3
  •   Vampire    8 年前

    TL;博士: 不要使用 Thread 中断作为中止标准,但改用一些自定义标志。


    Thread.sleep() InterruptedException ,但GDK Object.sleep() 处理和忽略中断: http://docs.groovy-lang.org/docs/groovy-2.4.7/html/groovy-jdk/java/lang/Object.html#sleep(long)

    任一使用 线睡眠()

    def t = Thread.start('name') {
        try {
            for (int i = 0; i < 10 && !Thread.interrupted(); ++i) {
                println i
                Thread.sleep 1000
            }
        } catch (InterruptedException e) {
            println "Catched exception"
        }
    }
    println "Interrupting thread in 1..."
    sleep 1000
    println "Interrupting thread..."
    t.interrupt()
    

    或者使用 对象睡眠() 用一个 Closure 例如:

    def t
    t = Thread.start('name') {
        try {
            for (int i = 0; i < 10 && !Thread.interrupted(); ++i) {
                println i
                sleep(1000) {
                    throw new InterruptedException()
                }
            }
        } catch (InterruptedException e) {
            println "Catched exception"
        }
    }
    println "Interrupting thread in 1..."
    sleep 1000
    println "Interrupting thread..."
    t.interrupt()
    

    在解决了你的困惑之后,现在让我建议你不要做你想做的事。中断绝不是作为中止条件使用的好方法。由于各种原因,睡眠或阻塞IO总是会被中断。更好的方法是让你的跑步循环检查一些 boolean 切换以中止工作的标志。