日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

iOS中NSThread使用示例詳解_IOS

作者:云層之上 ? 更新時間: 2022-11-28 編程語言

正文

NSThread的對象就代表一條線程,輕量級的線程操作,生命周期需要程序員控制,當任務執行完畢之后被釋放掉。

創建和啟動線程

有三種創建方式 代碼:

  • 1、 alloc init 創建線程,需要手動啟動線程
- (void)createNewThread1{
    //1.創建線程
    // 第三個參數object: 前面調用方法需要傳遞的參數 可以為nil
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"rc"];
    //設置線程的名字
    thread.name = @"線程RC";
    //設置優先級  取值范圍 0.0 ~ 1.0 之間 最高是1.0 默認優先級是0.5
    thread.threadPriority = 1.0;
    /*
     iOS8.0之后新增  線程優先級
     @property NSQualityOfService qualityOfService;
     NSQualityOfServiceUserInteractive --> Main thread
     NSQualityOfServiceUserInitiated   --> HIGH
     NSQualityOfServiceUtility         --> LOW
     NSQualityOfServiceBackground      --> Background
     NSQualityOfServiceDefault         --> Default
     */
   // thread.qualityOfService = NSQualityOfServiceDefault;    
    //2.啟動線程
    [thread start];
}
  • 2、分離子線程,自動啟動線程
-(void)createNewThread2{
    [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"分離子線程"];
}
  • 3、開啟一條后臺線程,自動啟動
-(void)createNewThread3{
    [self performSelectorInBackground:@selector(run:) withObject:@"開啟后臺線程"];
}
-(void)run:(NSString *)param{
    NSLog(@"---run----%@---%@",[NSThread currentThread],param);
}

打印:

RCNSThreadDemo[4644:223899] ---run----<NSThread: 0x600000a98480>{number = 3, name = 線程RC}---rc
RCNSThreadDemo[4644:223901] ---run----<NSThread: 0x600000a98a00>{number = 4, name = (null)}---分離子線程
RCNSThreadDemo[4644:223902] ---run----<NSThread: 0x600000a99740>{number = 5, name = (null)}---開啟后臺線程

  • 主線程相關用法
+ (NSThread *)mainThread; // 獲得主線程
- (BOOL)isMainThread; // 是否為主線程
+ (BOOL)isMainThread; // 是否為主線程
  • 獲得當前線程
NSThread *current = [NSThread currentThread];

線程的狀態

線程存在5種狀態:新建 、就緒、運行、阻塞、死亡

  • 啟動線程:進入就緒狀態 -> 運行狀態。當線程任務執行完畢,自動進入死亡狀態
 - (void)start; 
  • 阻塞(暫停)線程:進入阻塞狀態
+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
  • 強制停止線程:進入死亡狀態
 + (void)exit;

注意:一旦線程停止(死亡)了,就不能再次開啟任務

線程安全

因為同一塊資源可能會被多個線程共享,也就是多個線程可能會訪問同一塊資源,比如:比如多個線程訪問同一個對象、同一個變量、同一個文件 當多個線程訪問同一塊資源時,很容易引發數據錯亂和數據安全問題

蘋果官方提供的安全隱患分析圖:

如上圖:有2個線程A、B同時read同一個地址獲得17,A進行加1得到18后寫入,此時B將拿到的17進行加1得到18后再寫入。 很明顯的,17做了兩次+1的操作,最后得到結果卻是18!!! 對于這種多個線程訪問同一對象獲得的結果是不可以預期的就出現了安全隱患。 對此蘋果官方也給出了解決辦法:

如上圖:當ThreadA 在訪問資源之前,先添加了一把鎖,執行lock操作。再讀取資源, 執行+ 1 操作,結束后寫入,同時將資源解鎖,執行unlock操作。在這期間,其他的任何Thread是無法訪問這片資源的,必須等unlock操作結束后才可以訪。此時的其他Thread是出于等待狀態。

注意:加鎖是要消耗資源的

關于鎖可以看看這篇iOS線程鎖及其性能

再引申一下:

原子和非原子屬性

OC在定義屬性時有nonatomic和atomic兩種選擇,想必我們大部分人用的都是nonatomic

  • atomic:原子屬性,實際就是為setter方法加鎖(默認就是atomic),上面說過了,加鎖之后的線程是安全的,但是會消耗大量的資源。
  • nonatomic:非原子屬性,不會為setter方法加鎖,非線程安全,適合內存小的移動設備

建議是:所有屬性都聲明為nonatomic;盡量避免多線程搶奪同一塊資源;盡量將加鎖、資源搶奪的業務邏輯交給服務器端處理,減小移動客戶端的壓力。

下面模擬線程安全隱患,創建3個線程,從開始0作+1操作,直到大于10 停止 代碼:

//使用nonatomic定義屬性
@property (nonatomic,assign) NSInteger totalCount;
- (void)createSafeThread{
    self.threadA = [[NSThread alloc]initWithTarget:self selector:@selector(getTotal) object:nil];
    self.threadB = [[NSThread alloc]initWithTarget:self selector:@selector(getTotal) object:nil];
    self.threadC = [[NSThread alloc]initWithTarget:self selector:@selector(getTotal) object:nil];
    [self.threadA start];
    [self.threadB start];
    [self.threadC start];
}
- (void)getTotal{
    while (1) {
        NSInteger count = self.totalCount;
        if(count < 10) {
            // 添加一個耗時操作,效果更明顯
            for (NSInteger i = 0; i<88888; i++) {
                NSInteger a = 1; 
                NSInteger b = 1;
                a = a + b;
            }
            self.totalCount = count + 1;
            NSLog(@"--*-**----%ld",self.totalCount);
        }else{
            break;
        }
    }
}

我們預期的打印應該是:從1~10依次打印出來,但是我們看真實的打印結果:

打印:

// 截取部分打印
RCNSThreadDemo[1763:182366] ------1
RCNSThreadDemo[1763:182365] ------2
RCNSThreadDemo[1763:182364] ------2
RCNSThreadDemo[1763:182365] ------3
RCNSThreadDemo[1763:182364] ------4
RCNSThreadDemo[1763:182366] ------3
RCNSThreadDemo[1763:182365] ------5
RCNSThreadDemo[1763:182364] ------5
RCNSThreadDemo[1763:182366] ------6
RCNSThreadDemo[1763:182364] ------7

一眼就能看出有問題,其實如果用GCD來模擬會更加明顯,在并發隊列中for循環添加異步任務看來復制,會造成壞內存訪問而程序崩潰。

上面也說了添加一個互斥鎖就會解決以上問題,這里使用的是:

@synchronized

使用格式:@synchronized(鎖對象) { // 需要鎖定的代碼 },其中的鎖對象必須是唯一的,一般傳self或當前一個全局的變量,如self.threadA。

注意:鎖定1份代碼只用1把鎖,用多把鎖是無效的

互斥鎖的優缺點

  • 優點:能有效防止因多線程搶奪資源造成的數據安全問題
  • 缺點:需要消耗大量的CPU資源

使用前提:多條線程搶奪同一塊資源 互斥鎖會造成 線程同步 ,即多條線程在同一條線上執行(按順序地執行任務)

上代碼:

- (void)getTotal{
    while (1) {
        @synchronized (self) {
            NSInteger count = self.totalCount;
            if(count < 10) {
                // 添加一個耗時操作,效果更明顯
                for (NSInteger i = 0; i<88888; i++) {
                    NSInteger a = 1;
                    NSInteger b = 1;
                    a = a + b;
                }
                self.totalCount = count + 1;
                NSLog(@"------%ld",self.totalCount);
            }else{
                break;
            }
        }
    }
}

線程間通信

線程間通信常用方法

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;

以下載圖片為例: 代碼:

- (void)downloadImage{
    [NSThread detachNewThreadSelector:@selector(download) toTarget:self withObject:nil];
}
- (void)download{
    NSURL *url = [NSURL URLWithString:@"http://00.minipic.eastday.com/20170227/20170227134901_e45455144ba23b7cee75f292229151b1_21.jpeg"];
    NSData *imageData = [NSData dataWithContentsOfURL:url];
    UIImage *image = [UIImage imageWithData:imageData];
    //主線程顯示圖片  waitUntilDone :是否等待,指的是后面代碼的執行是否需要等待本次操作結束
    // 第一種
   // [self performSelector:@selector(showImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
    // 第二種
    [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
}
//更新UI操作
-(void)showImage:(UIImage *)image{
    self.imageView.image = image;
    NSLog(@"UI----%@",[NSThread currentThread]);
}

很簡單,開啟一個子線程來下載圖片,再去主線程更新UI。

原文鏈接:https://juejin.cn/post/7073298779772272676

欄目分類
最近更新