Groovy List 和 Map 循环扩展方法:支持可中断循环及闭包处理

本文将介绍一个为 Groovy 的 List 和 Map 集合添加可中断循环功能的扩展方法。该方法支持传入闭包作为循环体,并可以在循环过程中根据当前线程的状态自动结束循环,提高程序的健壮性。

扩展方法代码

// 扩展List类
static List eachWithInterruptible(Closure closure) {
    def interrupted = false
    each { item ->
        if (!interrupted) {
            closure.call(item)
            interrupted = Thread.interrupted()
        }
    }
}

// 扩展Map类
static Map eachWithInterruptible(Closure closure) {
    def interrupted = false
    each { key, value ->
        if (!interrupted) {
            closure.call(key, value)
            interrupted = Thread.interrupted()
        }
    }
}

使用示例

def list = [1, 2, 3, 4, 5]
list.eachWithInterruptible { item ->
    println(item)
    Thread.sleep(1000)
}

def map = [name: 'Tom', age: 18, gender: 'male']
map.eachWithInterruptible { key, value ->
    println('$key: $value')
    Thread.sleep(1000)
}

在上述示例中,我们分别使用了扩展的 List 和 Map 方法进行循环,传入了一个闭包作为循环体处理代码。在循环过程中,我们使用了 Thread.sleep() 方法模拟耗时操作。如果在循环过程中当前线程被打断,循环会自动结束。

总结

这个扩展方法可以方便地在 Groovy 代码中实现可中断循环,提高程序的健壮性,尤其是在处理耗时操作或需要响应外部事件的场景中非常有用。


原文地址: https://www.cveoy.top/t/topic/owiK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录