下面是一个实现了上述要求的groovy扩展方法:

// 扩展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为list集合或者Map扩展设计一个循环方法支持传入闭包做循环体处理代码对list或者Map做数据集用来循环同时循环过程中如果当前线程被打断时就退出循环自动结束

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

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