iOS学习笔记首页投稿(暂停使用,暂停投稿)将来跳槽用

iOS主要知识总结(网络多线程基础1NSThread)

2016-07-17  本文已影响78人  奕十八

iOS中实现多线程的几种方案

pThread

NSThread

/*
     第一个参数:目标对象 self
     第二个参数:方法选择器 线程创建之后要执行的任务
     第三个参数:传递给run:方法的参数
     */

    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"创建线程的第一种方法"];
    [thread start];
    [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"分离出一条子线程"];
    [self performSelectorInBackground:@selector(run:) withObject:@"创建一条后台线程"];
//设置线程的优先级 0.0 ~ 1.0 取值范围 最高是1.0 如果不设置那么默认是0.5
    threadA.threadPriority = 1.0;

线程安全问题

//给代码加一把同步锁
        //token 锁对象:全局唯一对象
        //注意点:1)加锁需要耗费性能
        //      2)注意加锁的位置
        //      3)注意加锁的条件:多线程访问同一块资源的时候

       @synchronized (self) {
}

NSThread线程间的通信问题

    [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:NO];
    [self performSelector:@selector(showImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];

如果单纯的是给imageView设置图片,我们可以借用系统的setImage方法,

    [self.imageView performSelectorOnMainThred:@selector(setImage:) withObject:image waitUntilDone:YES];

上一篇 下一篇

猜你喜欢

热点阅读