Operation的addDependency操作

我们有7个任务task1, task2, task3, task4, task5, task6, task7并发执行,要实现一个功能,task1,task2,task3执行完之后,在执行task4,task5执行完之后执行task6,task4和task6执行完之后,在执行task7

我们要建立线程依赖,task4.addDependency(task1),表明task4一定会在task1执行完之后在执行,所以代码如下

let task1 = BlockOperation{
    sleep(3)
    print("task1")
}

let task2 = BlockOperation{
    sleep(2)
    print("task2")
}
let task3 = BlockOperation{
    sleep(1)
    print("task3")
}
let task4 = BlockOperation{
    print("task4")
}
let task5 = BlockOperation{
    print("task5")
}
let task6 = BlockOperation{
    print("task6")
}
let task7 = BlockOperation{
    print("task7")
}
let queueOperation = OperationQueue()
task4.addDependency(task1)
task4.addDependency(task2)
task4.addDependency(task3)

task6.addDependency(task5)
task7.addDependency(task6)
task7.addDependency(task4)
queueOperation.addOperation(task1)
queueOperation.addOperation(task2)
queueOperation.addOperation(task3)
queueOperation.addOperation(task4)
queueOperation.addOperation(task5)
queueOperation.addOperation(task6)
queueOperation.addOperation(task7)

task1, task2, task3是异步执行的,但是task4一定在task1,task2,task3之后执行,task6一定在task5之后执行,task7一定在task4和task6之后执行,我电脑的打印顺序如下

task5
task6
task3
task2
task1
task4
task7

你可能感兴趣的:(Operation的addDependency操作)