iOS多線程--基礎篇NSThread

iOS開發用的線程發展主要有三個階段

NSTread、NSOpoperation、GCD

這篇文章主要講解基礎篇NSTread

一、NSTread的創建

    //NSTread 創建方式
    NSThread *oneThread = [[NSThread alloc] initWithTarget:self selector:@selector(test:) object:kurl];
    //設置線程優先級
    [oneThread setThreadPriority:0.5];
    //設置線程名稱
    [oneThread setName:@"oneThread"];
    //線程開始
    [oneThread start];
    //線程延時 阻塞
    [NSThread sleepForTimeInterval:60];
    //線程取消  取消可以再次開啓 退出不能開啓
    [oneThread cancel];
    //線程退出
    [NSThread exit];
    //另外一種創建方式,創建成功自動運行
    [NSThread detachNewThreadSelector:@selector(test) toTarget:self withObject:kurl];

    //獲取當前線程

    NSThread  *thread = [NSThread   currentThread];

    //判斷是否爲主線程

    BOOL result = oneThread.isMainThread;

    //更新UI都需要主線程來操作

    [self performSelectorOnMainThread:@selector(updateUI:) withObject:img waitUntilDone:YES];

   //更新其他線程執行操作

    performSelector:onThread:withObject:waitUntilDone: 

   上面寫到的只是一小部分,對於線程的操作控制基本上能想到的都會有對應的方法。

二、線程鎖問題

     NSLock:常用的鎖類 基本使用方法 調用統一方法 操作同一對象 簡單應用

- (void)run{
    while (TRUE) {
        // 上鎖
        [_theLock lock];
        if(tickets >= 0){
            [NSThread sleepForTimeInterval:0.09];
            count = 100 - tickets;
            NSLog(@"當前總數是:%d,減去:%d,線程名:%@",tickets,count,[[NSThread currentThread] name]);
            tickets--;
        }else{
            break;
        }

        //解鎖
        [_theLock unlock];
    }
}

iOS提供一種簡單編寫鎖事件的方式  @synchronized(anObj)  anObj這是

-(void)run:(nsstring *) anObj{

@synchronized(anObj)

{

         代碼塊需要加鎖的

}

}

總結

NSThread並不是主流的多線程使用方式可以作爲了解,回調主線程、一些簡單單一的線程可以使用。

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章