@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)button:(id)sender {
//子线程
// NSThread *th = [[NSThread alloc] initWithTarget:self selector:@selector(th:) object:nil];
// [th start];
[NSThread detachNewThreadSelector:@selector(th:) toTarget:self withObject:nil];
//线程互斥
//多线程队列
//创建队列
NSOperationQueue *q = [[NSOperationQueue alloc] init];
//在队列里创建添加子线程
[q addOperationWithBlock:^{
NSLog(@"q=%d",[[NSThread currentThread] isMainThread]);
//返回主线程的函数
[self performSelectorOnMainThread:@selector(mainThread:) withObject:nil waitUntilDone:YES];
}];
// 用NSInvocationOperation创建子线程
NSInvocationOperation *inv =[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(th:) object:nil];
[q addOperation:inv];
//GCD(c语言)创建线程
//1.创建队列
dispatch_queue_t queue = dispatch_queue_create("qq", NULL);
//2.创建子线程
dispatch_async(queue, ^{
//返回主线程
dispatch_sync(dispatch_get_main_queue(), ^{
});
});
}
-(void)th:(id)object
{
NSLog(@"th=%d",[[NSThread currentThread] isMainThread]);
NSURL *url = [NSURL URLWithString:BaseUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
UIImage *image = [UIImage imageWithData:data];
[self performSelectorOnMainThread:@selector(mainThread:) withObject:image waitUntilDone:YES];
}
-(void)mainThread:(id)object
{
self.imageV.image = object;
}
@end