课程来自慕课网不死鸟fj老师
pThread
- (void)clickPThread {
NSLog(@"主线程");
pthread_t pthread;
pthread_create(&pthread, NULL, run, NULL);
}
void *run(void *data) {
NSLog(@"子线程");
for (int i = 1; i < 10; i++) {
NSLog(@"%d",i);
sleep(1);
}
return NULL;
}
NSThread的创建和执行
- 通过 alloc init 方式创建并执行线程
NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(runThread1) object:nil];
[thread1 setName:@"Name_Thread1"]; // 设置线程名称
[thread1 setThreadPriority:0.2]; // 设置线程优先级 0-1
[thread1 start];
- 通过 detachNewThreadSelector 方式创建并执行线程
[NSThread detachNewThreadSelector:@selector(runThread1) toTarget:self withObject:nil];
- 通过 performSelectorInBackground 方式创建线程
[self performSelectorInBackground:@selector(runThread1) withObject:nil];
NSThread锁
-(void)sale {
while (true) {
@synchronized (self) {
if (self.tickets > 0) {
[NSThread sleepForTimeInterval:0.5];
self.tickets--;
self.soldCount = Total - self.tickets;
NSLog(@"%@: 当前余票: %d, 售出: %d",[NSThread currentThread].name,self.tickets,self.soldCount);
}
}
}
}
GCD的创建
// 获取全局并发队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 获取主队列
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_async(queue, ^{
// 异步追加任务
for (int i = 0; i < 2; ++i) {
[NSThread sleepForTimeInterval:2]; // 模拟耗时操作
NSLog(@"1---%@",[NSThread currentThread]); // 打印当前线程
}
// 回到主线程
dispatch_async(mainQueue, ^{
// 追加在主线程中执行的任务
[NSThread sleepForTimeInterval:2]; // 模拟耗时操作
NSLog(@"2---%@",[NSThread currentThread]); // 打印当前线程
});
});
// 串行队列的创建方法
dispatch_queue_t queue = dispatch_queue_create("com.test.gcd.queue", DISPATCH_QUEUE_SERIAL);
// 并发队列的创建方法
dispatch_queue_t queue = dispatch_queue_create("com.test.gcd.queue", DISPATCH_QUEUE_CONCURRENT);
GCD_Group
NSLog(@"GCD开始执行");
dispatch_queue_t queue = dispatch_queue_create("com.test.gcd.group", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
[self sendRequest1:^{
NSLog(@"request1 done");
dispatch_group_leave(group);
}]
[self sendRequest2:^{
NSLog(@"request2 done");
dispatch_group_leave(group);
}]
// dispatch_group_async(group, queue, ^{
// NSLog(@"start task 1");
// [NSThread sleepForTimeInterval:2];
// NSLog(@"end task 1");
// });
// dispatch_group_async(group, queue, ^{
// NSLog(@"start task 2");
// [NSThread sleepForTimeInterval:2];
// NSLog(@"end task 2");
// });
dispatch_group_notify(group, queue, ^{
NSLog(@"All tasks over");
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"回到主线程刷新UI");
});
});
NSOperation
NSOperation是个抽象类,并不具备封装操作的能力,必须使⽤它的子类
使用NSOperation⼦类的方式有3种:
(1)NSInvocationOperation
(2)NSBlockOperation
(3)自定义子类继承NSOperation,实现内部相应的⽅法