美文网首页
iOS多线程操作:NSThread

iOS多线程操作:NSThread

作者: zevwings | 来源:发表于2019-07-21 12:08 被阅读0次

在我们开发过程中我们经常会用到多线程开发,比如在异步线程中加载资源,执行好使操作等,在iOS开发中常见的多线程操作主要有Thread(NSThread)Operation(NSOperation)GCD这几种方式,我们下面来一一了解这些多线程操作方式。

ThreadObjective-C中为NSThread这种线程操作方式最多的在我们使用对象调用方法时,使用perform(_:on:with:waitUntilDone:modes:)方法。但是Thread也可以作为开辟一个新线程的方式。

首先我们学习它的初始化方法,我们可以通过Selector或者闭包的方式初始化一个新方法,然后通过start方法开启这个线程。

// 使用`Selector`方式创建Thread
thread2 = Thread(target: self, selector: #selector(asynExecute(_:)), object: nil)
// 方便调试,添加name
thread2.name = "thread 2"
// 开始执行线程
thread2.start()

// 使用闭包方式创建`Thread`
thread1 = Thread {
  for i in 0...100 {
      // 休眠1秒
      Thread.sleep(forTimeInterval: 1)
      print("thread 1 \(i)")
      print("thread 1 isCanceled \(self.thread1.isCancelled)")
      print("thread 1 isExecuting \(self.thread1.isExecuting)")
      // 判断thread2 是否执行完毕
      if self.thread2.isFinished {
          print("thread 2 is finished ")
          // 终止thread1
          print("current \(Thread.current.name ?? "")")
                  // 取消当前线程,但是没有取消循环执行???
          self.thread1.cancel()
                    // 终止当前线程执行
                    Thread.exit()
      }
  }
}
// 方便调试,添加name
thread1.name = "thread 1"
// 开始执行线程
thread1.start()

@objc func asynExecute(_ thread: Thread) {
    for i in 0...100 {
        // 休眠 0.5s
        Thread.sleep(forTimeInterval: 0.5)
        print("thread 2 \(i)")
    }
}

执行上述代码,我们可以看到结果,thread2和thread1交替执行。

thread 2 0
thread 1 0
thread 1 isCanceled false
thread 1 isExecuting true
thread 2 1
thread 2 2
thread 1 1
thread 1 isCanceled false
thread 1 isExecuting true
thread 2 3
thread 2 4
......
thread 1 isCanceled false
thread 1 isExecuting true
thread 2 is finished 
current thread 1

我们也可以通过集成Thread来创建一个线程,集成Thread并重写main方法即可。

class AsyncThread: Thread {
    override func main() {
        for i in 0 ... 100 {
            print(i)
        }
    }
}   

let thread = AsyncThread()
thread.start()

Thread的用法比较简单,我们可以方便的用来开启线程,当然这只是Thread最基本的用发,我们也可以通过isMainThread判断是否为主线程,更多的方法可以阅读Thread相关文档。

更好的阅读体验可以参考个人网站:https://zevwings.com

相关文章

网友评论

      本文标题:iOS多线程操作:NSThread

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