【iOS开发】多线程 - 概述

2017-09-21  本文已影响13人  Huangbaoqin



// way1,该线程立刻退出,若果该线程退出前线程中申请的资源没有释放容易造成内存泄漏
+ (void)exit
// way2,不作特殊处理该线程会继续执行
- (void)cancel
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    _thread1 = [[NSThread alloc] initWithBlock:^{
        NSLog(@"thread start");
        for (NSInteger i = 0; i <= 100; i ++) {
            NSLog(@"%@ --- %ld", _thread1, (long)i);
            sleep(1);
            if ([[NSThread currentThread] isCancelled]) {
                break;
            }
        }
        NSLog(@"thread end");
    }];
    [_thread1 start];
}

#pragma mark - Button methods

- (IBAction)handleCancelThread:(id)sender {
    [_thread1 cancel];
    _thread1 = nil;
}

+ (BOOL)isMainThread; // 当前的代码执行的线程是否是主线程
+ (NSThread *)currentThread; // 当前代码执行的线程
+ (NSThread *)mainThread; // 获取主线程
+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
@interface NSObject (NSThreadPerformAdditions)
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
- (void)performSelectorInBackground:(SEL)aSelector withObject:(nullable id)arg
@end


线程开销
上一篇 下一篇

猜你喜欢

热点阅读