- 线程
- 主线程
- 后台线程
-
线程是被模拟出来的,CPU通过分配时间片的方法模拟出多线程
CPU通过分配时间片的方法模拟出多线程
-
NSThread创建一个线程
- 对象方法
// 对象方法 NSThread *thread1 = [[NSThread alloc] initWithBlock:^{ ... }]; [thread1 start];
- 类方法
// 类方法 [NSThread detachNewThreadWithBlock:^{ ... }];
- 继承对象
@interface testThread : NSThread @end @implementation testThread - (void)main { ... } @end
// 继承方法 testThread *thread_t = [[testThread alloc] init]; thread_t.delegate = self; [thread_t start];
-
线程的状态
线程的状态
-
优雅的取消一个线程
// 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;
}
![](https://img.haomeiwen.com/i752708/9a53bf0ff2817812.jpg)
- 线程相关的方法
+ (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
-
多线程优点
- 提高APP实时响应性能
- 充分利用计算资源
-
多线程缺点
- 线程安全
- 复杂度提升
- 需要额外的系统开销
- 线程的开销
![](https://img.haomeiwen.com/i752708/53784d3cb6eafbfc.jpg)
-
线程同步问题
-
线程同步的方法
- NSLock
@protocol NSLocking // 访问变量前后使用 - (void)lock; - (void)unlock; @end @interface NSLock : NSObject <NSLocking> { @private void *_priv; } - (BOOL)tryLock; - (BOOL)lockBeforeDate:(NSDate *)limit; @property (nullable, copy) NSString *name API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); @end
- synchronized
@synchronized (self) { a ++; }
-
死锁
网友评论