//
// ViewController.m
// 12-barrier使用
//
// Created by gzxzmac on 16/1/29.
// Copyright © 2016年 gzxzmac. All rights reserved.
//
#import "ViewController.h"
@interface ViewController () {
dispatch_queue_t _queue;
}
@property (nonatomic, strong) NSMutableArray *photoList; // 保存下载好的图片
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self download];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSLog(@"下载了 %zd 张图片",self.photoList.count);
}
// 最快速创建一个可变的数组 @[].mutableCopy
- (NSMutableArray *)photoList {
if (_photoList == nil) {
_photoList = [NSMutableArray array];
}
return _photoList;
}
- (void)download {
// NSArray,字典,NSData,..... 线程安全
// 所有的可变的对象(字典,数组,data) 非线程安全
/*
NSArchiver
NSAutoreleasePool
NSBundle
NSCalendar
NSCoder
NSCountedSet
NSDateFormatter
NSEnumerator
NSFileHandle
NSFormatter
NSHashTable functions
NSInvocation
NSJavaSetup functions
NSMapTable functions
NSMutableArray
NSMutableAttributedString
NSMutableCharacterSet
NSMutableData
NSMutableDictionary
NSMutableSet
NSMutableString
NSNotificationQueue
NSNumberFormatter
NSPipe
NSPort
NSProcessInfo
NSRunLoop
NSScanner
NSSerializer
NSTask
NSUnarchiver
NSUndoManager
*/
// 一定要使用自定义的并发队列
_queue = dispatch_queue_create("itcast", DISPATCH_QUEUE_CONCURRENT);
for (int i = 0; i < 1000; ++i) {
dispatch_async(_queue, ^{
NSLog(@"下载图片%d",i);
[NSThread sleepForTimeInterval:0.5];
// 模拟下载
NSString *imageName = [NSString stringWithFormat:@"%d.jpg",i % 9];
NSString *path = [[NSBundle mainBundle]pathForResource:imageName ofType:nil];
UIImage *image = [UIImage imageWithContentsOfFile:path];
// 使用barrier 之后,全部下载完之后,再统一保存
// 减少多条线程抢夺资源的问题
// 在工作中基本不怎么使用(知道)
dispatch_barrier_async(_queue, ^{
if (image == nil) {
NSLog(@"%d -- %@",i,path);
}
NSLog(@"保存图片%@",[NSThread currentThread]);
// 避免多个线程抢同一块资源
[self.photoList addObject:image];
});
});
}
}
@end
多线程:barrier的使用
最新推荐文章于 2022-11-27 23:20:01 发布