第一种需手动开启
1.
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(runFor) object:nil];
[thread start];
线程需自动开启
2.
[NSThread detachNewThreadSelector:@selector(runFor) toTarget:self withObject:nil];
第二种的线程自
1.
NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(runFor) object:nil];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[queue addOperation:operation];
2.
- (void)createOperation{
NSBlockOperation *block = [NSBlockOperation blockOperationWithBlock:^{
for (int i = 0; i < 10; i++) {
NSLog(@"%d",i);
}
[self runFor];
}];
NSLog(@"NSBlockOperation == %s",__func__);
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[queue addOperation:block];
NSOBject自带的线程
[self performSelectorInBackground:@selector(runFor) withObject:self];
GCD主要使用
- (void)action{
// //GCD 全名grand central dispatch
// //并发执行的队列 DISPATCH_QUEUE_CONCURRENT
// //还有一个同步DISPATCH_QUEUE_SERIAL
// dispatch_queue_t concurrent = dispatch_queue_create("1", DISPATCH_QUEUE_CONCURRENT);
// //异步执行队列,将block中的代码添加到创建的队列中
// dispatch_async(concurrent, ^{
// for (int i = 0; i < 10; i++) {
// NSLog(@"i == %d",i);
// }
// });
// dispatch_async(concurrent, ^{
// for (int j = 0; j < 10; j++) {
// NSLog(@"j == %d",j);
// }
// });
//
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *url = [NSURL URLWithString:@"http://img3.douban.com/view/event_poster/hlarge/public/365aa3c50b5ba01.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
NSLog(@"%s",__func__);
dispatch_async(dispatch_get_main_queue(), ^{
[self.imageView setImage:image];
NSLog(@"%s",__func__);
});
// [self performSelectorOnMainThread:@selector(myAction:) withObject:image waitUntilDone:YES];
//
});
}