iOS 多线程

iOS 多线程系列 -- NSThread

2017-06-27  本文已影响56人  shannoon

iOS 多线程系列 -- 基础概述
iOS 多线程系列 -- pthread
iOS 多线程系列 -- NSThread
iOS 多线程系列 -- GCD全解一(基础)
iOS 多线程系列 -- GCD全解二(常用方法)
iOS 多线程系列 -- GCD全解三(进阶)
iOS 多线程系列 -- NSOperation
测试Demo的GitHub地址

1.NSThread基础

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[thread start];// 启动线程,在线程thread中执行self的run方法
+ (NSThread *)mainThread; // 获得主线程
- (BOOL)isMainThread; // 是否为主线程
+ (BOOL)isMainThread; // 是否为主线程
NSThread *current = [NSThread currentThread];
- (void)setName:(NSString *)n;
- (NSString *)name;

//示例:
thread.name = @"my-thread";

//创建线程后自动启动线程
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"XL"];
//隐式创建并启动线程
[self performSelectorInBackground:@selector(run:) withObject:@"OC"];

2 控制线程状态的方法有:

2.1 启动线程

启动线程
- (void)start;
// 进入就绪状态 -> 运行状态。当线程任务执行完毕,自动进入死亡状态
[thread start];

2.2 阻塞(暂停)线程

+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
// 调用这个方法的线程进入阻塞状态,
[NSThread sleepForTimeInterval:2];
//第二种线程暂停睡眠的方法
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];
//遥远的未来才开始运行,相当于一直停止
[NSThread sleepUntilDate:[NSDate distantFuture]];

2.3 强制停止线程 ,

+ (void)exit;// 这是一个类方法,调用这个方法的所在线程会进入死亡状态
[NSThread exit];
   
- (void)createThreadCancel
{
    XLThread *thread = [[XLThread alloc] initWithTarget:self selector:@selector(runCancel) object:@"XL"];
    thread.name = @"cancel-thread";
    [thread start];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"before thread.isCancelled = %zd",thread.isCancelled);
        [thread cancel];
        NSLog(@"after thread.isCancelled = %zd",thread.isCancelled);
    });
}

- (void)runCancel
{
    for (NSInteger i = 0; i<10000; i++) {
        NSLog(@"-----%zd , [NSThread currentThread] = %@", i , [NSThread currentThread]);
        sleep(0.01);
        if ([NSThread currentThread].isCancelled) {
            // 进行线程退出前的一些操作,如内存回收等
            [NSThread exit]; // 线程退出,其后面的代码不会被执行 , 或者调用return;
            NSLog(@"-----exit [NSThread currentThread] = %@" , [NSThread currentThread]);
        }
    }
}

3 多线程的安全隐患

    - (void)saleTicket
    {
        while (1) {
            @synchronized(self) {
                // 先取出总数
                NSInteger count = self.ticketCount;
                if (count > 0) {
                    self.ticketCount = count - 1;
                    NSLog(@"%@卖了一张票,还剩下%zd张", [NSThread currentThread].name, self.ticketCount);
                } else {
                    NSLog(@"票已经卖完了");
                    break;
                }
            }
        }
    }

4 线程间通信

// 方法1
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array;
// 方法2
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
// equivalent to the first method with kCFRunLoopCommonModes
// 方法3
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array NS_AVAILABLE(10_5, 2_0);
// 方法4
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait NS_AVAILABLE(10_5, 2_0);
// equivalent to the first method with kCFRunLoopCommonModes
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self performSelectorInBackground:@selector(download3) withObject:nil];
}
- (void)download3
{
    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];
}
- (void)showImage:(UIImage *)image
{
    self.imageView.image = image;
}

5. NSThread和NSRunloop结合使用 - 常驻线程

- (void)runPerformWithRunloop {
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    [runLoop addPort:[NSPort port] forMode:NSDefaultRunLoopMode];//RunLoop中没有事件源、定时器等,进入RunLoop后就会立即推出RunLoop,留不住线程 , 所以必须添加一个port源
    while (![[NSThread currentThread] isCancelled]) {// 检查线程的isCancelled状态,如果线程状态被设置为canceled,就退出线程,否则就继续进入runloop,10s后退出runloop重新判断线程的最新状态
        [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:10]];  //⑤启动runloop ,10s后退出runloop
    }
}
注意点:
- (void)run;
- (void)runUntilDate:(NSDate *)limitDate;
- (BOOL)runMode:(NSRunLoopMode)mode beforeDate:(NSDate *)limitDate;
上一篇 下一篇

猜你喜欢

热点阅读