NSThread
方法1
[NSThread detachNewThreadSelector:@selector(threadAction1) toTarget:self withObject:nil];
主线程默认是1m,其他线程是512byte
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(threadAction1) object:nil];
[thread start];
分类:脱离线程
+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument
方法执行完后会自动回收
非脱离线程
任务执行完后不会自动回收,需要手动回收
方法2 使用NSObject分类中的方法
[id performSelectorInBackground:@selector(threadAction1) withObject:nil];
// 放在主线程中执行(界面刷新只能在主线程执行,子线程主要是做比较耗时的操作,防止卡死主线程)
[self performSelectorOnMainThread:@selector(threadAction2) withObject:nil waitUntilDone:YES];
/**
* 若方法是在子线程中必须添加释放池
*/
- (void)threadAction1
{
// 防止程序崩溃,减少堆空间的使用
@autoreleasepool {
NSLog(@"Current Thread2 %@", [NSThread currentThread]);
for (int i = 0; i < 10000000; i++) {
NSLog(@"线程1-----%d", i);
}
}
}
- (void)threadAction2
{
@autoreleasepool {
NSLog(@"Current Thread3 %@", [NSThread currentThread]);
for (int i = 0; i < 10; i++) {
NSLog(@"线程2");
}
}
}
方法3
通过操作队列的方式进行(是一种非脱离的,即可实现线程的重用)
NSOperationQueue *quene = [[NSOperationQueue alloc]init];
NSInvocationOperation *nsInvocation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(threadAction1) object:nil];
[quene addOperation:nsInvocation];
队列的特点是先进先出,所以可以添加多个NSOperationQuene对象,执行的顺序是先进去的先执行
线程同步:串行,存在任务等的时间(要实现同步操作只要设置queue1.maxConcurrentOperationCount = 1)即可
线程异步:并行执行(以下方法实现了线程的同步)
quene.maxConcurrentOperationCount = 1;
NSInvocationOperation *nsInvocation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(threadAction1) object:nil];
//在那个线程中执行就会在那个线程中执行
[nsInvocation start];
// 其中执行的一个是主线程,一个是子线程,是通过并行的方式
NSBlockOperation *block = [NSBlockOperation blockOperationWithBlock:^{
[self threadAction1];
}];
[block addExecutionBlock:^{
[self threadAction2];
}];
[block addExecutionBlock:^{
[self threadAction2];
}];
[block addExecutionBlock:^{
[self threadAction2];
}];
NSOperationQueue *queue1 = [[NSOperationQueue alloc]init];
NSBlockOperation *block = [NSBlockOperation blockOperationWithBlock:^{
[self threadAction1];
}];
NSBlockOperation *block1 = [NSBlockOperation blockOperationWithBlock:^{ [self threadAction1]; }]; NSBlockOperation *block2 = [NSBlockOperation blockOperationWithBlock:^{ [self threadAction1]; }]; [queue1 addOperation:block]; [queue1 addOperation:block1];
[queue1 addOperation:block2];使用block进行线程操作也是通过线程并发执行的