ios 异步线程 NSLock 小结

来源:互联网 发布:2017北京云计算大会 编辑:程序博客网 时间:2024/05/18 22:16

1

    dispatch_queue_t q =dispatch_queue_create("thread-one",DISPATCH_QUEUE_SERIAL) ;    dispatch_async(q, ^{     //to  do    });     // 获取 名字的方法     // NSLog(@"%s", dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2

   NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(display) object:nil];    thread.name = @"thread-three";    [thread start];
  • 1
  • 2
  • 3
  • 4

swfit 
1

     let queue1 = DispatchQueue(label: "thread-one")        queue1.async {        // to do ;        }
  • 1
  • 2
  • 3
  • 4

2

      let thread1 = Thread(target: self, selector: #selector(ViewController.display), object: nil)        thread1.name = "thread1"        thread1.start()
  • 1
  • 2
  • 3

Nslock使用

 let thread1 = Thread(target: self, selector: #selector(ViewController.display), object: nil)        thread1.name = "thread1"        thread1.start()        let thread2 = Thread(target: self, selector: #selector(ViewController.display), object: nil)        thread2.name = "thread2"        thread2.start()        let thread3 = Thread(target: self, selector: #selector(ViewController.display), object: nil)        thread3.name = "thread3"        thread3.start()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
    func display(){       // lock.lock() //打开            //耗时操作            self.name =  Thread.current.name! ;            //            Thread.sleep(forTimeInterval: TimeInterval(5))                    print("\(self.name) -- \(Thread.current.name!) ")       // lock.unlock()//打开    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

输出

thread2 -- thread3 thread2 -- thread1 thread2 -- thread2 
  • 1
  • 2
  • 3

混乱了,修改display方法 注释打开 输出

thread3 -- thread3 thread1 -- thread1 thread2 -- thread2 
  • 1
  • 2
  • 3

正常了

   func display(){       lock.lock()            self.name =  Thread.current.name!        let timer:Timer = Timer(timeInterval: 5.0,                                target: self,                                selector: #selector(ViewController.log),                                userInfo: nil,                                repeats: false)        // 将定时器添加到运行循环        RunLoop.current.add(timer, forMode: RunLoopMode.defaultRunLoopMode)        RunLoop.current.run()       lock.unlock()    }    func log(){      print("\(self.name) -- \(Thread.current.name!) ")        Thread.sleep(forTimeInterval: 10);    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

如果 lock 的内容 有异步执行的 会等异步执行完 再解锁 上面 一共过了 15s 才解锁

原创粉丝点击