iOS開發多線程基礎知識

來源:互聯網
上載者:User

標籤:class   blog   http   tar   ext   com   

--------------------------多線程概念基礎-------進程:正在啟動並執行程式記憶體:每個進程所佔的儲存空間線程:1個進程要像執行任務,必須得有線程,線程是進程的基本執行單元,線程的串列:·1個線程中人物的執行是串列的·0同一個時間內,1個線程只能執行1個任務0·線程是進程的一條執行路徑--------多線程·一個進程中可以開啟多條線程,每條線程可以並行(同時)同時執行不同的任務·進程-》車間  線程-》車間工人線程的並行:·進程內多個線程同時執行,可提高程式的執行效率---多線程的原理·同一時間,cpu只能處理一條線程,只有1條線程在工作(執行)·多線程並發(同時)執行,其實是cpu快速的在多條線程之間調度(切換)·若cpu調度線程的時間足夠快,就造成了多線程並發執行的假象·思考:線程非常多,會發生什麼:》cpu繪製n多線程之間調度,cpu會累死,消耗大量的cpu資源》每條線程被調度執行的頻次會降低(線程的執行效率降低)---多線程的優缺點-·多線程的優點:·1.能是低昂提高程式的執行效率·2.能適當提高資源使用率(cpu,記憶體利用率)-·多線程的缺點:·1.開啟線程需要佔用一定的記憶體空間,若開啟大量現場,會佔用大量的記憶體空間,降低程式效能·2.線程越多,cpu在調度線程刪搞定開銷就越大·3.程式設計更加複雜:比如線程之間的通訊、多線程的資料共用-------------------------多線程在iOS開發中的的應用--------·一。主線程1.一個iOS程式運行後,預設會開啟1條線程,稱為“主線程”or“UI線程”2.主線程的主要作用·顯示、重新整理UI介面·處理UI事件(點擊,滾動,拖拽)3.主線程的使用注意:·別將比較耗時的操作放在主線程中(影響UI流暢性)·若將耗時操作放在主線程,主線程是串列執行,使用者會感覺很卡,使用者體驗會很差二。耗時操作的執行1.若將耗時操作放在子線程(後天線程,非主線程)·好處:①在使用者點擊按鈕的那一刻就有反應;②能同時處理耗時操作和UI控制項的事件三。iOS中多線程的實現方案1.pthread:c語言①一套統一的多線程API②使用與Unix、Linux、Windows等系統③跨平台、可移植④使用難度比較大⑤.程式員管理線程聲明周期⑥.使用頻率:幾乎不用2.NSThread:OC語言①使用更加物件導向②簡單易用,可直接操作線程對象③。線程聲明周期:程式員管理④。偶爾使用3.GCD :c語言①指標替代NSThread等線程技術②重複利用裝置的多核③。線程生命週期:自動管理④使用頻率:經常使用4.NSOperation OC語言①基於GCD(底層是GCD)②比GCD多了一些更堅定的功能③使用更加物件導向③。線程生命週期:自動管理④使用頻率:經常使用-------建立和啟動線程--1.一個NSThread對象就代表一條線程2.建立、啟動線程NSThread *thread = [[NSThread alloc] initWithTarget:self selector(run) object:nil];[thread start];// 線程一啟動,就會線上程thread中執行self的run方法3.主線程相關用法+ (NSThread *)mainThread; // 獲得主線程- (BOOL)isMainThread; // 是否為主線程+ (BOOL)isMainThread; // 是否為主線程-----其它用法--1.獲得當前線程NSThread *current = [NSThread currentThread];2.線程的調度優先順序+ (double)threadPriority;+ (BOOL)setThreadPriority:(double)p;- (double)threadPriority;- (BOOL)setThreadPriority:(double)p;調度優先順序的取值範圍是0.0 ~ 1.0,預設0.5,值越大,優先順序越高3.線程的名字- (void)setName:(NSString *)n;- (NSString *)name;-------建立線程的3種方式----/** *  NSThread建立方式3:隱世線程建立,並且直接(自動)啟動線程 */- (void)threadCreate3{    [self performSelectorInBackground:@selector(run:) withObject:@"333333"];}/** *  建立方式2:建立完線程後自動啟動線程 */- (void)threadCreate2{    // 分離出的子線程    [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"2222222"];}/** *  建立方式1:①先建立初始化子線程②再啟動 */- (void)threadCreate{    NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"heheh"];    thread1.name = @"thread1";    // 開啟線程    [thread1 start];        NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"heheh"];    thread2.name = @"thread2";    // 開啟線程    [thread2 start];        NSThread *thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"heheh"];    thread3.name = @"33";    // 開啟線程    [thread3 start];}----·~方法2,3相對於方法1的優缺點·優點:簡單快捷·確定:無法對線程進行更詳細的設定-----------------線程的5種狀態--------建立 就緒  運行  阻塞  死亡NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"heheh"];代碼執行完,在記憶體中建立一個線程對象,它處於建立狀態不會運行,然後調用[thread1 start];記憶體中會出現一個可調度線程池,start狀態之後,建立的線程從 建立狀態變為就緒狀態,等待cpu的調度,cpu一旦調度,就會從就緒狀態變為運行狀態;期間若cpu調度其它線程對象,線程對象又變成就緒狀態,再調度再進入運行狀態。若調用了sleep方法、等待同步鎖,那麼線程對象會先進入阻塞狀態,它會可調度線程池中清除線程任務執行完畢、異常、強制退出,線程對象進入死亡狀態,線程對象也會從線程調度池中移除,但是還在記憶體中。-----------控制線程狀態------1。啟動線程- (void)start;// 進入就緒狀態 - 》 運行狀態。當鹹菜任務執行完畢,自動進入死亡狀態2.阻塞(暫停)線程+ (void)sleepUntilDate:(NSDate *)date;+ (void)sleepForTimeInterval:(NSTimeInterval)ti;// 進入阻塞狀態3.強制停止線程+ (void)exit;// 進入死亡狀態,注意:一旦進入死亡狀態,線程就不能再用了// notice:一旦線程tingzhil,就不嫩哥在此開啟任務--------------線程的安全問題(多線程的安全隱患)-------1.資源共用·一塊資源可能會被多個線程共用,即多個線程可能會訪問同一塊資源·比如多個線程訪問同一個對象,同一個變數、同一個檔案2.當多個線程訪問同一塊資源時,很容易引發資料錯亂和資料安全問題3.執行個體eg。1 存錢取錢eg。2 賣票-----------------安全隱患解決-互斥鎖-----1.格式@synchronized(鎖對象){// 需要鎖定的代碼}注意:鎖定一份代碼只能用1把鎖,用多把鎖是無效的2.優缺點·優點:能有效防止多線程搶奪資源造成的安全問題·缺點:需要消耗大量的cpu資源3.互斥鎖的使用前提:多條線程搶奪同一塊資源4.相關術語:線程同步·means:多條線程按順序的執行任務·互斥鎖就是使用了線程同步技術-----------------原子和非原子屬性----------------------1.OC在定義屬性時有nonatomomic和atomic兩種選擇·atomic:原子屬性,為setter方法加鎖(預設就是atomic)·nonatomic:非原子屬性,不會為setter方法加鎖2.atomic加鎖原理@property (assign, atomic) int age;- (void)setAge:(int)age{    @synchronized(self)    {        _age = age;    }}----------原子和非原子屬性的選擇----1.nonatomic和atomic對比·atomic:安全執行緒,需要消耗大量資源·nonatomic:非安全執行緒,適合記憶體小的行動裝置2.iOS開發的建議·所有屬性都聲明為nonatomic·盡量避免多線程搶奪同一塊資源·盡量將加鎖、資源搶奪的商務邏輯交給伺服器端處理,減小移動用戶端的壓力-----------------線程間的通訊----------------------1.什麼叫線程間的通訊·在一個進程中,線程往往不是鼓勵挫折的,多個線程之間需要進行通訊2.線程間通訊的體現·一個線程傳遞資料給另一個線程·在一個線程中執行完特定任務後,轉到另一個線程繼續執行任務3.線程間通訊常用方法- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;----------------GCD---------------1.GCD 全稱:Grand Central Dispatch,可譯為“偉大的中樞調度器”,純c語言,提供了飛奪強大的函數2.GCD的優勢·GCD是蘋果公司為多核的並行運算提出的解決方案·GCD會自動利用更多的CPU核心(比如雙核、四核)·GCD會自動管理線程的生命週期(建立線程、調度任務、銷毀線程)·程式員只需要告訴GCD想要執行什麼任務,不需要編寫任何線程管理代碼------GCD的任務和隊列--1.GCD中又2個核心概念:·任務:執行什麼操作·隊列:用來存放任務2.GCD的使用就2個步驟·①定製任務:·》確定想做的事情·②將任務添加到隊列中:·》GCD會自動將隊列中的任務取出,放到對應的線程中執行·》任務的取出遵循隊列的FIFO原則:先進先出,後進後出----GCD執行任務-----1.GCD中有2個用來執行任務的函數·用同步的方式執行任務dispatch_sync(dispatch_queue_t queue, dispatch_block_t block)·》queue:隊列·》block:任務·用非同步方式執行任務dispatch_async(dispatch_queue_t queue, dispatch_block_t block);2.同步和非同步區別·同步:在當前線程中執行·非同步:在另一條線程中執行-------GCD的隊列類型----1.GCD的隊列可以分為兩大類型·並發隊列(Concurrent Dispatch Queue)》可以讓多個任務並發(同時)執行(自動開啟多個線程同時執行任務)》並發功能只有在非同步函數(dispatch_async)中才有效·串列隊列(Serial Dispatch Queue)》讓任務一個接著一個的執行(一個任務執行完畢後,在執行下一個任務)---------GCD中容易混淆的術語----1.有四個術語比較容易混淆:同步、非同步、並發、串列·同步和非同步決定了要不要開啟新的線程·》同步:在當前線程中執行任務,不具備開啟新線程的能力·》非同步:在新的線程中執行任務,具備開啟新線程的能力·並發和串列決定了任務的執行方式·》並發:多個任務並發(同時)執行·》串列:一個任務執行完畢後,再執行下一個任務---GCD的並發隊列---1.GCD預設已經提供了全域的並發隊列,供整個應用使用,不需要手動建立·使用dispatch_get_global_queue函數獲得全域的並發隊列dispatch_queue_t dispatch_get_global_queue(dispatch_queue_priority_t priority, //隊列的優先順序                                           unsigned long flags; // 此參數暫時無用,用0即可);dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // 獲得全域並發隊列2.全域並發隊列的優先順序·#define DISPATCH_QUEUE_PRIORITY_HIGH 2 // 高·#define DISPATCH_QUEUE_PRIORITY_DEFAULT 0 // 預設(中)·#define DISPATCH_QUEUE_PRIORITY_LOW (-2) // 低·#define DISPATCH_QUEUE_PRIORITY_BACKGROUND INT16_MIN //後台----GCD的串列隊列----1.GCD中獲得串列有2種途徑·使用dispatch_queue_create函數差ungjchuanx隊列dispatch_queue_tdispatch_queue_create(const char *label, // 隊列名稱dispatch_queue_attr_t attr // 隊列屬性,一般用NULL即可);dispatch_queue_t queue = dispatch_queue_create("cn.itcast.queue", NULL); // 建立dispatch_release(queue); // 非ARC需要是轟動釋放建立的隊列·使用主隊列(跟主線程相關聯的隊列)·》主隊列是GCD內建的一種特殊的串列隊列·》放在主隊列中的任務,都會放到主線程中執行·》使用dispatch_get_main_queue()獲得主隊列dispatch_queue_t queue = dispatch_get_main_queue();-----GCD各種隊列的執行效果----/** *  使用dispatch_async非同步函數,在主線程中網主隊列中新增工作 */- (void)testAsyncMainQueue {    // 1.獲得主隊列    dispatch_queue_t queue = dispatch_get_main_queue();    // 2.新增工作到隊列中,執行任務    dispatch_async(queue, ^{        NSLog(@"---------1-----%@", [NSThread currentThread]);    });        // 總結:不開新線程    }/** *  使用dispatch_sync同步函數,在主線程中網主隊列中新增工作,死:任務無法往下執行 */- (void)testSyncMainQueue {    // 1.獲得主隊列    dispatch_queue_t queue = dispatch_get_main_queue();    // 2.新增工作到隊列中,執行任務    dispatch_sync(queue, ^{        NSLog(@"---------1-----%@", [NSThread currentThread]);    });            // 總結:不開新線程,所有任務在主線程中串列執行}// 凡是函數名中帶有create、copy、new、retain等字眼,都需要在不需要使用這個資料的時候進行release// GCD的資料類型在ARC環境下不需要再做release// CF(Core Foundation)的資料類型在ARC環境下仍然要做release- (void)testCF {    CFArrayRef array = CFArrayCreate(NULL, NULL, 11, NULL);    CFRelease(array);}/** *  用dispatch_sync同步函數往串列隊列中新增工作 */- (void)testSyncSerialQueue {    // 1.建立串列隊列    dispatch_queue_t queue = dispatch_queue_create("cn.dongyue.queue", NULL);        // 2.新增工作到隊列中,執行任務    dispatch_sync(queue, ^{        NSLog(@"---------1-----%@", [NSThread currentThread]);    });    dispatch_sync(queue, ^{        NSLog(@"---------2-----%@", [NSThread currentThread]);    });    dispatch_sync(queue, ^{        NSLog(@"---------3-----%@", [NSThread currentThread]);    });        // 3.釋放(MRC)    //dispatch_release(queue);            // 總結:不會開新的線程}/** *  用dispatch_sync同步函數往並發隊列中新增工作 */- (void)testSyncGlobalQueue {    // 1.獲得全域的並發隊列    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);        // 2.新增工作到隊列中,執行任務    dispatch_sync(queue, ^{        NSLog(@"---------1-----%@", [NSThread currentThread]);    });    dispatch_sync(queue, ^{        NSLog(@"---------2-----%@", [NSThread currentThread]);    });    dispatch_sync(queue, ^{        NSLog(@"---------3-----%@", [NSThread currentThread]);    });        // 總結:不會開啟新的線程,並發隊列失去了並發功能}/** *  用dispatch_async同步函數往並發隊列中新增工作 */- (void)testAsyncSerialQueue {    // 1.建立串列隊列    dispatch_queue_t queue = dispatch_queue_create("cn.dongyue.queue", NULL);        // 2.新增工作到隊列中,執行任務    dispatch_async(queue, ^{        NSLog(@"---------1-----%@", [NSThread currentThread]);    });    dispatch_async(queue, ^{        NSLog(@"---------2-----%@", [NSThread currentThread]);    });    dispatch_async(queue, ^{        NSLog(@"---------3-----%@", [NSThread currentThread]);    });        // 總結:只開1個新的線程,不會開啟新的線程}/** *  用dispatch_async同步函數往並發隊列中新增工作 */- (void)testAsyncGlobalQueue {    // 1.獲得全域的並發隊列    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);        // 2.新增工作到隊列中,執行任務    dispatch_async(queue, ^{        NSLog(@"---------1-----%@", [NSThread currentThread]);    });    dispatch_async(queue, ^{        NSLog(@"---------2-----%@", [NSThread currentThread]);    });    dispatch_async(queue, ^{        NSLog(@"---------3-----%@", [NSThread currentThread]);    });    // 總結:同時開啟了3個線程}----------線程間通訊樣本---------1.從子線程回到主線程(下載圖片)- (void)testBackToMain {    // 擷取全域並發隊列    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);    // 非同步隊列    dispatch_async(queue, ^{        NSLog(@"-----%@", [NSThread currentThread]);        // 下載圖片        NSString *path = @"圖片連結的網址";        NSURL *url = [NSURL URLWithString:path];        NSData *data = [NSData dataWithContentsOfURL:url];                UIImage *image = [UIImage imageWithData:data];        // 回到主線程顯示圖片        dispatch_async(dispatch_get_main_queue(), ^{            NSLog(@"-----------%@", [NSThread currentThread]);            self.iconView.image = image;        });    });}--------GCD的延時執行----1.iOS常見的延時執行有2種方式·調用NSObject的方法[self performSelector:@selector(run) withObject:nil afterDelay:2.0];// 2秒後再調用self的run方法·使用GCD函數- (void)testDelay {    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{        NSLog(@"222");    });}---------一次性代碼------ (void)testOnce {    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        NSLog(@"once");    });}------------隊列組------1.有這麼一種需求·首先:分別非同步執行2個耗時的操作·其次:等2各非同步作業都執行完畢後,再回到主線程執行操作2.若想要快速高效的實現上述需求,可以考慮用隊列組- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{    NSLog(@"%@", [NSThread currentThread]);    dispatch_group_t group = dispatch_group_create();    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);        __block UIImage *icon1 = nil;    dispatch_group_async(group, queue, ^{        NSLog(@"%@", [NSThread currentThread]);        //        icon1 = [self imageWithURL:@"http://image.cache.xiu8.com/live/125/125/997729.jpg"];            });    __block UIImage *icon2 = nil;    dispatch_group_async(group, queue, ^{        NSLog(@"%@", [NSThread currentThread]);        //        icon2 = [self imageWithURL:@"http://news.baidu.com/z/resource/r/image/2014-06-22/b2a9cfc88b7a56cfa59b8d09208fa1fb.jpg"];    });        dispatch_group_notify(group, dispatch_get_main_queue(), ^{        NSLog(@"%@", [NSThread currentThread]);        //        self.iconV1.image = icon1;        self.iconV2.image = icon2;                UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 100), NO, 0);        [icon1 drawInRect:CGRectMake(0, 0, 100, 100)];        [icon2 drawInRect:CGRectMake(100, 0, 100, 100)];        self.bigIconV.image = UIGraphicsGetImageFromCurrentImageContext();                UIGraphicsEndImageContext();    });}- (UIImage *)imageWithURL:(NSString *)iconPath{    NSLog(@"%@", [NSThread currentThread]);    NSURL *url = [NSURL URLWithString:iconPath];    NSData *data = [NSData dataWithContentsOfURL:url];    return [UIImage imageWithData:data];}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.