//第一种方式 手动创建并启动
NSThread *t = [[NSThread alloc] initWithTarget:self selector:@selector(method) object:nil];
[t start];
//第二种方式 类方法
[NSThread detachNewThreadSelector:@selector(method) toTarget:self withObject:nil];
//第三种方式 类方法
[self performSelectorInBackground:@selector(method) withObject:nil];
//第四种方式 block 语法
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
//会开启一个多线程,调用block
[operationQueue addOperationWithBlock:^{
for (int i=0; i<50; i++) {
NSLog(@"多线程:%d", i);
}
}];
//第五种 线程队列(线程池)
NSOperationQueue *operationQueue2 = [[NSOperationQueue alloc] init]; //相当于一个线程池,里面可以放很多线程,这个线程池管理多个线程的调度,可以给线程设置优先级,并发数
operationQueue2.maxConcurrentOperationCount = 1; //设置最大并发数量(并发=同时进行)
//创建线程
NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(thread1) object:nil];
//设置线程的优先级
[operation1 setQueuePriority:NSOperationQueuePriorityVeryLow];
NSInvocationOperation *operation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(thread1) object:nil];
[operation2 setQueuePriority:NSOperationQueuePriorityVeryHigh];
//将线程添加到线程池
[operationQueue2 addOperation:operation1];
[operationQueue2 addOperation:operation2];
//----------------------回到主线程--------------------------------
//在多线程中可能加载数据,加载完了之后要刷新ui, ui必须在主线程上面操作,在多线程的方法中这样调用
[self performSelectorOnMainThread:@selector(thread1) withObject:nil waitUntilDone:YES];
//-----------------第六种线程的使用方式--------------
//这个函数是C的函数,字符串test也要用C里面的字符串,是不带@符号的
dispatch_queue_t queue = dispatch_queue_create("test", NULL);
dispatch_async(queue, ^{
for (int i=0; i<50; i++) {
NSLog(@"多线程:%d", i);
}
//回到主线程执行
dispatch_async(dispatch_get_main_queue(), ^{
if ([NSThread isMainThread]) {
NSLog(@"是主线程");
}
});
});
-(void)thread1 {
//这里是开启了一个新的线程,所以新的线程跟主线程脱离关系了,这个里面的内存管理,我们需要自己创建一个自动释放池
//创建自动释放池
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSLog(@"执行多线程");
[pool release];
}