網(wǎng)絡上很多文章都寫了多線程的4種組合
同步+串行 琐谤, 異步+串行 蟆技, 同步+并行 ,異步+并行
在同一條線程中使用斗忌,不再贅述质礼,網(wǎng)上都是這類。
但是在多個線程中使用的話织阳,會有區(qū)別眶蕉,體現(xiàn)了串行隊列和并行隊列的特性。
比如兩個任務唧躲,兩個子線程造挽,各處理一個碱璃,在各自線程中使用串行+同步的話,原以為這兩個任務沒有影響饭入,會在各自線程中執(zhí)行嵌器,無序的。但是結(jié)果是這兩個任務是順序執(zhí)行的谐丢。
代碼如下
self.queue = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT);
NSThread *thread1 = [[NSThread alloc] initWithBlock:^{
dispatch_async(self.queue, ^{
[NSThread sleepForTimeInterval:3];
NSLog(@"線程 %@ 1", [NSThread currentThread]);
});
}];
[thread1 start];
NSThread *thread2 = [[NSThread alloc] initWithBlock:^{
dispatch_async(self.queue, ^{
[NSThread sleepForTimeInterval:3];
NSLog(@"線程 %@ 2", [NSThread currentThread]);
});
}];
[thread2 start];