標籤:style blog http color os 使用 io for 資料
1、什麼叫做線程間通訊
在1個進程中,線程往往不是孤立存在的,多個線程之間需要經常進行通訊
2、線程間通訊的體現
1個線程傳遞資料給另1個線程
在1個線程中執行完特定任務後,轉到另1個線程繼續執行任務
3、線程間通訊樣本
UIImageView下載圖片這個例子, 主線程中開啟一個子線程去下載圖片, 當圖片下載完成之後再回到主線程中更新顯示圖片, 這樣的一個過程就是線程間通訊的一個過程.
4、NSThread線程間通訊常用方法
// 第一種
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
// 第二種- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;
5、使用NSThread多線程間通訊
1 - (void)viewDidLoad 2 { 3 [super viewDidLoad]; 4 5 // 使用多線程來下載圖片 6 [NSThread detachNewThreadSelector:@selector(downloadImage) toTarget:self withObject:nil]; 7 } 8 9 - (void)downloadImage10 {11 NSLog(@"開始下載圖片 %@", [NSThread currentThread]);12 13 // 下載的方法14 // 1. url網路資源15 NSURL *url = [NSURL URLWithString:@"http://pic12.nipic.com/20110124/4814485_135921152102_2.jpg"];16 17 // 2. OC原生的方法,網路上的所有資料都是以“二進位或者字串”的方式傳遞的18 // 在以後的開發中,幾乎不用,因為效能太差19 NSData *data = [NSData dataWithContentsOfURL:url];20 21 // 3. 根據下載的資料建立映像22 UIImage *image = [UIImage imageWithData:data];23 24 NSLog(@"完成下載圖片 %@", [NSThread currentThread]);25 26 // 更新UI,需要在主線程上進行27 // waitUntilDone:是否等待setImage:方法結束28 [self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];29 }
以上代碼是用NSThread多線程方式實現子線程下載圖片,在主線程更新UI的操作
上邊這段代碼是有問題的,應該在多線程上加一個自動釋放池
6、使用GCD完成多線程間通訊
1 - (void)viewDidLoad 2 { 3 [super viewDidLoad]; 4 5 // 下載圖片 6 [self downloadImage]; 7 } 8 9 - (void)downloadImage10 {11 // 1. 全域並行隊列12 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);13 14 // 2. 非同步任務15 dispatch_async(queue, ^{16 NSLog(@"開始下載圖片 %@", [NSThread currentThread]);17 18 // 下載的方法19 // 1. url網路資源20 NSURL *url = [NSURL URLWithString:@"http://img.pconline.com.cn/images/upload/upc/tx/wallpaper/1208/30/c0/13398570_1346308990114_800x600.jpg"];21 22 // 2. OC原生的方法,網路上的所有資料都是以“二進位或者字串”的方式傳遞的23 // 在以後的開發中,幾乎不用,因為效能太差24 NSData *data = [NSData dataWithContentsOfURL:url];25 26 // 3. 根據下載的資料建立映像27 UIImage *image = [UIImage imageWithData:data];28 29 NSLog(@"完成下載圖片 %@", [NSThread currentThread]);30 31 // 4. 通知主隊列更新UI32 // 給主隊列,添加一個非同步任務,更新UI33 dispatch_async(dispatch_get_main_queue(), ^{34 self.image = image;35 });36 });37 }
與NSThread方式相比,不用考慮自動釋放池的問題,而且非同步任務的操作都是放在塊代碼中,比較集中,可讀性好。
iOS中多線程_05_線程間通訊NSThread/GCD