我們有7個(gè)任務(wù)task1, task2, task3, task4, task5, task6, task7并發(fā)執(zhí)行,要實(shí)現(xiàn)一個(gè)功能,task1缴川,task2,task3執(zhí)行完之后描馅,在執(zhí)行task4把夸,task5執(zhí)行完之后執(zhí)行task6,task4和task6執(zhí)行完之后铭污,在執(zhí)行task7
我們要建立線程依賴恋日,task4.addDependency(task1),表明task4一定會(huì)在task1執(zhí)行完之后在執(zhí)行,所以代碼如下
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是異步執(zhí)行的嘹狞,但是task4一定在task1岂膳,task2,task3之后執(zhí)行磅网,task6一定在task5之后執(zhí)行谈截,task7一定在task4和task6之后執(zhí)行,我電腦的打印順序如下
task5
task6
task3
task2
task1
task4
task7