多线程知识点之NSThread的使用

/********线程的状态**************************************/

 线程的状态:新建状态(New)--->就绪状态(Runnable)----->运行状态(Running)---->阻塞状态(Blocked)---->死亡状态(Dead)

启动线程

- (void)start;

// 进入就绪状态 -> 运行状态。当线程任务执行完毕,自动进入死亡状态

阻塞(暂停)线程

+ (void)sleepUntilDate:(NSDate *)date;

+ (void)sleepForTimeInterval:(NSTimeInterval)ti;

//    [NSThread sleepForTimeInterval:2]; // 让线程睡眠2秒(阻塞2秒)

//    [NSThread sleepUntilDate:[NSDate distantFuture]];

// 进入阻塞状态

强制停止线程

+ (void)exit;

// 进入死亡状态

/********多线程安全隐患的解决方法(互斥锁)**************************************/

互斥锁使用格式

@synchronized(锁对象) { // 需要锁定的代码  }

注意:锁定1份代码只用1把锁,用多把锁是无效的,一般用控制器对象self作为锁对象

互斥锁的优缺点
优点:能有效防止因多线程抢夺资源造成的数据安全问题
缺点:需要消耗大量的CPU资源
 
互斥锁的使用前提:多条线程抢夺同一块资源
 
相关专业术语:线程同步
线程同步的意思是:多条线程在同一条线上执行(按顺序地执行任务)
互斥锁,就是使用了线程同步技术
 
OC在定义属性时有nonatomic和atomic两种选择
atomic:原子属性,为setter方法加锁(默认就是atomic)
nonatomic:非原子属性,不会为setter方法加锁
 
atomic:线程安全,需要消耗大量的资源
nonatomic:非线程安全,适合内存小的移动设备
 
/********多线程间通信**************************************/
线程间通信常用方法

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;

- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;

线程间另一种通信方式 – 利用NSPort

NSPort;

NSMessagePort;

NSMachPort;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    //开启一条子线程

    [self performSelectorInBackground:@selector(download) withObject:nil];

}

// 子线程方法

- (void)download

{

    // 图片的网络路径

    NSURL *url = [NSURL URLWithString:@"http://img.pconline.com.cn/images/photoblog/9/9/8/1/9981681/200910/11/1255259355826.jpg"];

    // 加载图片

    NSData *data = [NSData dataWithContentsOfURL:url];

    // 生成图片

    UIImage *image = [UIImage imageWithData:data];

    // 回到主线程,显示图片

    [self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO];

//    [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];

//    [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES];

}

/********NSThread开启线程的三种方式方式@"jack"(线程的名字)*****/

- (void)createThread3

{

    [self performSelectorInBackground:@selector(run:) withObject:@"jack"];

}

- (void)createThread2

{

    [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"rose"];

}

- (void)createThread1

{

       // 创建线程

       NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"jack"];

       // 启动线程

      [thread start];

}

原文地址:https://www.cnblogs.com/wangliang2015/p/5407041.html