DispatchQueue에서 코드 블록을 호출하는데 DispatchWorkItem을 활용하여 코드 블록을 캡슐화해줄 수 있음
클로저의 사용과 비슷하게 사용
물론, 클로저를 코드 블록 내부에서 호출해주어도 상관없음
DispatchWorkItem을 이용하면 타입을 명시하는 동시에 더 직관적인 코드를 작성할 수 있음
DispatchWorkItem는 sync, async 메서드의 execute파라미터를 통해 전달하면 됨
import Foundation
let red = DispatchWorkItem {
for _ in 1...5 {
print("🥵🥵🥵🥵🥵")
sleep(1)
}
}
let yellow = DispatchWorkItem {
for _ in 1...5 {
print("😀😀😀😀😀")
sleep(1)
}
}
let blue = DispatchWorkItem {
for _ in 1...5 {
print("🥶🥶🥶🥶🥶")
sleep(2)
}
}
DispatchQueue.main.async(execute: yellow)
DispatchQueue.global().sync(excute: blue)
// 1 - red안됨
DispatchQueue.global().async(execute: yellow)
DispatchQueue.global().sync(execute: blue)
DispatchQueue.main.async(execute: red)
😀😀😀😀😀
🥶🥶🥶🥶🥶
🥶🥶🥶🥶🥶
😀😀😀😀😀
🥶🥶🥶🥶🥶
😀😀😀😀😀
🥶🥶🥶🥶🥶
😀😀😀😀😀
🥶🥶🥶🥶🥶
😀😀😀😀😀
// 2
DispatchQueue.global().sync(execute: yellow)
DispatchQueue.global().async(execute: blue)
DispatchQueue.main.async(execute: red)
😀😀😀😀😀
😀😀😀😀😀
😀😀😀😀😀
😀😀😀😀😀
😀😀😀😀😀
🥶🥶🥶🥶🥶
// 3
DispatchQueue.main.async(execute: yellow)
DispatchQueue.global().async(execute: blue)
DispatchQueue.global().sync(execute: red)
🥶🥶🥶🥶🥶
🥵🥵🥵🥵🥵
🥵🥵🥵🥵🥵
🥶🥶🥶🥶🥶
🥵🥵🥵🥵🥵
🥶🥶🥶🥶🥶
🥵🥵🥵🥵🥵
🥶🥶🥶🥶🥶
🥵🥵🥵🥵🥵
🥶🥶🥶🥶🥶
// 4
DispatchQueue.main.async(execute: yellow)
DispatchQueue.global().sync(execute: blue)
DispatchQueue.global().async(execute: red)
🥶🥶🥶🥶🥶
🥶🥶🥶🥶🥶
🥶🥶🥶🥶🥶
🥶🥶🥶🥶🥶
🥶🥶🥶🥶🥶
🥵🥵🥵🥵🥵
🥵🥵🥵🥵🥵
🥵🥵🥵🥵🥵
🥵🥵🥵🥵🥵
🥵🥵🥵🥵🥵
DispatchQueue.global().asyncAfter(deadline: .now() + 5, execute: yellow)
DispatchQueue.global().asyncAfter(deadline: .now() + 5, execute: yellow)
DispatchQueue.global().asyncAfter(wallDeadline: .now() + 5, excute: blue)