多线程的一些注意事项

NSThread创建线程:
1.NSThread*thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[thread start];
2.[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
3.[self performSelectorInBackground:@selector(run) withObject:nil];

多线程存在安全隐患,容易引起争抢资源,造成数据混乱。要解决这个问题,需要用到互斥锁:
@synchronized(self) { // 需要锁定的代码  }
注意:锁定1份代码只用1把锁,用多把锁是无效的

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

GCD
执行任务有2种方式:
同步:dispatch_sync(dispatch_queue_tqueue, dispatch_block_tblock);
异步:dispatch_async(dispatch_queue_tqueue, dispatch_block_tblock);

队列有两种:
并发:苹果提供了全局队列:dispatch_queue_tqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // 获得全局并发队列
串行:苹果提供了主队列,放在主队列中的任务,都会放到主线程中执行:dispatch_queue_tqueue = dispatch_get_main_queue();
也可以自己创建串行队列:dispatch_queue_tqueue = dispatch_queue_create("cn.yunjun.queue", NULL); // 创建
dispatch_release(queue); // ARC需要释放手动创建的队列

线程间通信
dispatch_async(
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // 执行耗时的异步操作...
      dispatch_async(dispatch_get_main_queue(),
^{
        // 回到主线程,执行UI刷新操作
        });
});

延时执行
[self performSelector:@selector(run)
withObject:nil afterDelay:2.0];
// 2秒后再调用selfrun方法

dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
(int64_t)(2.0 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
    // 2秒后异步执行这里的代码...   
});

一次性代码:单例模式常用
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    // 只执行1次的代码(这里面默认是线程安全的)
});

队列组:组内任务全部执行完再执行别的操作
dispatch_group_tgroup = dispatch_group_create();
dispatch_group_async(group,
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // 执行1个耗时的异步操作
});

dispatch_group_async(group,
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // 执行1个耗时的异步操作
});

dispatch_group_notify(group,
dispatch_get_main_queue(), ^{
    // 等前面的异步操作都执行完毕后,回到主线程...
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值