Swift 多线程-串行调度队列(Serial queue)

使用Serial queue处理并发任务

1.单条队列
import UIKit

class ViewController: UIViewController {

@IBOutlet var imageViewArr: [UIImageView]!

let imageUrls = ["https://xxx.com/1.jpg","https://xxx.com/2.jpg","https://xxx.com/3.jpg","https://xxx.com/4.jpg"]


override func viewDidLoad() {
    super.viewDidLoad()

}

@IBAction func downloadImages(sender: UIButton) {
    
      // Add task
    let serialQueue1 = dispatch_queue_create(
        "task1", DISPATCH_QUEUE_SERIAL)
    dispatch_async(serialQueue1) { () -> Void in
        for  i in 0..<4 {
            let imageViewUrls = Downloader.downloadImageWithURL(self.imageUrls[i])
    // UI需要在主线程下更新
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.imageViewArr[i].image = imageViewUrls
                //self.imageViewArr[i].clipsToBounds = true
            })

        }
    }
        
    
}
@IBAction func ClearDownData(sender: UIButton) {
    
    for i in 0...3 {
        imageViewArr[i].image = nil
    }

}

}

// -------------

class Downloader {

class func downloadImageWithURL(url:String) -> UIImage! {
    let data = NSData(contentsOfURL: NSURL(string: url)!)
    return UIImage(data: data!)
}
}
1.1多条队列
    let serialQueue1 = dispatch_queue_create(
        "task1", DISPATCH_QUEUE_SERIAL)
        dispatch_async(serialQueue1) { () -> Void in
            let image0 = Downloader.downloadImageWithURL(self.imageUrls[0])
            let image2 = Downloader.downloadImageWithURL(self.imageUrls[1])

            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.imageViewArr[0].image = image0
                self.imageViewArr[2].image = image2
       })
    }
        
    let serialQueue2 = dispatch_queue_create("task2", DISPATCH_QUEUE_SERIAL)
        dispatch_async(serialQueue2, { () -> Void in
            let image1 = Downloader.downloadImageWithURL(self.imageUrls[1])
            let image3 = Downloader.downloadImageWithURL(self.imageUrls[3])

            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.imageViewArr[1].image = image1
                self.imageViewArr[3].image = image3
            })

            
        })
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容