ios 异步线程 NSLock 小结

来源:互联网 发布:织梦cms仿站教程 编辑:程序博客网 时间:2024/05/19 01:12

oc
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));

2

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

swfit
1

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

2

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

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()
    func display(){       // lock.lock() //打开            //耗时操作            self.name =  Thread.current.name! ;            //            Thread.sleep(forTimeInterval: TimeInterval(5))                    print("\(self.name) -- \(Thread.current.name!) ")       // lock.unlock()//打开    }

输出

thread2 -- thread3 thread2 -- thread1 thread2 -- thread2 

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

thread3 -- thread3 thread1 -- thread1 thread2 -- thread2 

正常了

   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);    }

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

0 0
原创粉丝点击