美文网首页
IOS多线程

IOS多线程

作者: 79d12e22ec53 | 来源:发表于2019-04-28 19:05 被阅读0次

多线程技术

Thread

//
//  ViewController.swift
//  TestDemo
//
//  Created by 1320-hym on 2019/4/12.
//  Copyright © 2019年 1320-hym. All rights reserved.
//

import UIKit
import Alamofire

class ViewController: UIViewController {

    var imageView: UIImageView!
    var label: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        imageView = UIImageView(frame: CGRect(x: 0, y: 260, width: 320, height: 300))
        self.view.addSubview(imageView)
        
        label = UILabel(frame: CGRect(x: 0, y: 0, width: 320, height: 200))
        label.text = "loading"
        self.view.addSubview(label)
        
        let imgUrl = "http://images.apple.com/v/iphone/home/s/home/images/trade_in_iphone_large_2x.jpg"
        let thread = Thread(target: self, selector: #selector(ViewController.downloadImage), object: imgUrl)
        
        thread.start()

    }
    
    @objc func downloadImage(path: String) {
        
        let url = URL(string: path)
        var data: Data!
        do{
            try data = Data(contentsOf: url!)
            let image = UIImage(data: data)
//            self.perform(Selector:(showImage), on: Thread.main, with: image, waitUntilDone: true)
            self.perform(#selector(ViewController.showImage), on: Thread.main, with: image, waitUntilDone: true)
        }catch{
            print("下载失败")
        }
    }
    
    @objc func showImage(image: UIImage) {
        self.imageView.image = image
        self.label.isHidden = true
    }
    


}


给线程加锁使线程同步

//如果不用线程可能会造成书的库存为负数


import UIKit
import Alamofire

class ViewController: UIViewController {

    var booksCount = 100
    var soldBooksCount = 0
    var lock: NSLock!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        lock = NSLock()
        
        let salesmanA = Thread(target: self, selector: #selector (ViewController.sellBook), object: nil)
        salesmanA.name = "销售员A"
        salesmanA.start()
        
        
        let salesmanB = Thread(target: self, selector: #selector (ViewController.sellBook), object: nil)
        salesmanB.name = "销售员B"
        salesmanB.start()
        
        
        let salesmanC = Thread(target: self, selector: #selector (ViewController.sellBook), object: nil)
        salesmanC.name = "销售员C"
        salesmanC.start()

    }
    
    @objc func sellBook() {
        
        while true {
            lock.lock()
            if booksCount > 0 {
                Thread.sleep(forTimeInterval: 0.01)
                
                soldBooksCount += 1
                booksCount -= 1
                let threadname = Thread.current.name
                
                print("当前销售员为:\(String(describing: threadname)), 此时已售书:\(soldBooksCount), 还剩余\(booksCount)")
            }else{
                Thread.exit()
            }
            lock.unlock()
        }
        
    }
    



}

Operation

//
//  ViewController.swift
//  TestDemo
//
//  Created by 1320-hym on 2019/4/12.
//  Copyright © 2019年 1320-hym. All rights reserved.
//

import UIKit
import Alamofire

class ViewController: UIViewController {


    var topImageView = UIImageView()
    var footIamgeView = UIImageView()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        topImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 320, height: 280))
        self.view.addSubview(topImageView)
        
        footIamgeView = UIImageView(frame: CGRect(x: 0, y: 280, width: 320, height: 290))
        self.view.addSubview(footIamgeView)
        
        let downloadA = getOperation(name: "下载线程A", imageUrl: "http://images.apple.com/v/watch/k/images/overview/watch_03_large.jpg", isTopOne: true)
        
        let downloadB = getOperation(name: "下载线程B", imageUrl: "http://images.apple.com/v/watch/k/images/overview/watch_05_large.jpg", isTopOne: false)
        
        let queue = OperationQueue()
        queue.maxConcurrentOperationCount = 1
        queue.addOperation(downloadA)
        queue.addOperation(downloadB)
        
        for operation in queue.operations{
            print("operation name:" + operation.name!)
        }
        

    }


    
    func getOperation(name: String, imageUrl: String, isTopOne: Bool) -> BlockOperation{
        
        let download = BlockOperation(block: {
            
            let url = URL(string: imageUrl)
            var data: Data!
            do{
                Thread.sleep(forTimeInterval: 1.0)
                try data = Data(contentsOf: url!)
                let image = UIImage(data: data)
                if isTopOne {
                    self.perform(#selector(ViewController.showTopImage), on:Thread.main, with: image, waitUntilDone: true)
                } else {
                    self.perform(#selector(ViewController.showFootImage), on:Thread.main, with: image, waitUntilDone: true)
                }
            } catch{
                print("下载失败")
            }
            
        })
        
        download.name = name
        return download
        
    }

    
    @objc func showTopImage(image: UIImage) {
        self.topImageView.image = image
    }
    
    @objc func showFootImage(image: UIImage) {
        self.footIamgeView.image = image
    }

}


相关文章

网友评论

      本文标题:IOS多线程

      本文链接:https://www.haomeiwen.com/subject/nehngqtx.html