多线程

UIview只能在主线程里
自定义一个线程时要重写-  (void)main
添加到非主队列里的操作都并发执行,且都在子线程


//
//  ViewController.m
//  ThreadApp
//
//  Created by apple on 14-9-11.
//  Copyright (c) 2014年 戴维营教育. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

- (IBAction)didClick:(id)sender;
@property (weak, nonatomic) IBOutlet UILabel *label;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self download:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//1. 线程有独立的栈空间
//2. 执行顺序随机
- (IBAction)didClick:(id)sender {
    static int i = 0;
    
//    [NSThread sleepForTimeInterval:10];
    
    i++;
    [self performSelectorInBackground:@selector(download:) withObject:@(i)];
    i++;
    
    //***
    [self performSelectorInBackground:@selector(download:) withObject:@(i)];
    
//    [NSURLConnection sendAsynchronousRequest:<#(NSURLRequest *)#> queue:<#(NSOperationQueue *)#> completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//        <#code#>
//    }];
}

- (void)download:(id)object
{
//    NSLog(@"----starting----");
//    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://class.room/tinghai.mp3"]];
//    NSLog(@"%lu", data.length);
    
    for (int i = 0; i < 100000; i++) {
        NSLog(@"%@: %d", object, i);
        
//        _label.text = [NSString stringWithFormat:@"%d", i];
        
        NSString *str = [NSString stringWithFormat:@"%d", i];
        //在主线程中执行setText方法
        //*******
//        [_label performSelectorOnMainThread:@selector(setText:) withObject:str waitUntilDone:YES];
//        [self performSelectorOnMainThread:@selector(setText:) withObject:str waitUntilDone:YES];
        
        [self performSelector:@selector(setText:) onThread:[NSThread mainThread] withObject:str waitUntilDone:YES modes:@[NSDefaultRunLoopMode]];
        NSLog(@"....");
    }
}

- (void)setText:(NSString *)text
{
    _label.text = text;
    
    //****
    NSLog(@"%@", [NSThread isMainThread]?@"Main Thread":@"Not Main Thread");
}
@end


//
//  ViewController.m
//  ThreadApp2
//
//  Created by apple on 14-9-11.
//  Copyright (c) 2014年 戴维营教育. All rights reserved.
//

#import "ViewController.h"

#import "MyThread.h"
#import "Downloader.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //1. 创建子线程
//    [self performSelectorInBackground:<#(SEL)#> withObject:<#(id)#>];
    
    //2. 创建了一个新的子线程
//    [NSThread detachNewThreadSelector:@selector(print) toTarget:self withObject:nil];
    
    //3. 通过创建NSThread对象的方式实现多线程
//    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(print) object:nil];
//    [thread start];
//    [thread cancel];
    
    //4. 继承NSThread
//    MyThread *thread = [[MyThread alloc] init];
//    [thread start];
    
    Downloader *downloader = [[Downloader alloc] init];
    downloader.path = @"http://class.room/tinghai.mp3";
    downloader.completionHandler = ^(NSData *data){
        NSLog(@"download completion: %lu", data.length);
        NSLog(@"%@", [NSThread isMainThread]?@"Main":@"Not");
    };
    [downloader start];
}

- (void)print
{
    NSLog(@"%@", [NSThread isMainThread]?@"Main":@"Not Main");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

//操作线程
//
//  ViewController.m
//  NSOperation-0911
//
//  Created by apple on 14-9-11.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //默认为主线程
//    NSInvocationOperation *invOper=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(print:) object:nil];
//    [invOper start];
    
    
    //fangfaQianMing
//    NSMethodSignature *methSignt=[self methodSignatureForSelector:@selector(print:obj2:)];
//    //方法调用
//    NSInvocation *invocation=[NSInvocation invocationWithMethodSignature:methSignt];
//    [invocation setTarget:self];
//    [invocation setSelector:@selector(print:obj2:)];
//    
//    //设置参数
//    NSString *str=@"abc";
//    NSNumber *num=@122;
//    [invocation setArgument:&str atIndex:2];
//    [invocation setArgument:&num atIndex:3];
//    //调用方法
//    [invocation invoke];
//    NSInvocationOperation *invocationOper=[[NSInvocationOperation alloc]initWithInvocation:invocation];
//    [invocationOper start];
    
    
//    NSBlockOperation *blockOper=[NSBlockOperation blockOperationWithBlock:^{
//        NSLog(@"----%@",[NSThread isMainThread]?@"IS":@"NO");
//    }];
//    
//    [blockOper addExecutionBlock:^{
//        NSLog(@"++==%@",[NSThread isMainThread]?@"IS":@"NO");
//    }];
//    
//    [blockOper start];
    
    
    NSInvocationOperation *op1=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(print:) object:@1];
    NSInvocationOperation *op2=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(print:) object:@2];
    NSInvocationOperation *op3=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(print:) object:@3];
    NSInvocationOperation *op4=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(print:) object:@4];
    //执行操作,并发执行
//    NSOperationQueue *queue=[[NSOperationQueue alloc]init];
    //主队列可以保证都是在主线程
    NSOperationQueue *queue=[NSOperationQueue mainQueue];
    [queue addOperation:op1];
    [queue addOperation:op2];
    [queue addOperation:op4];
    [queue addOperation:op3];

    [queue addOperationWithBlock:^{
        NSLog(@"%@",[NSThread isMainThread]?@"IS":@"NO");
    }];
    
}

- (void)print:(id)obj
{
    NSLog(@"%@  %@",obj,[NSThread isMainThread]?@"IS":@"No");
}

- (void)print:(id)object obj2:(id)object2
{
    NSLog(@"%@, %@,%@: %@", self,NSStringFromSelector(_cmd), object, object2);
    NSLog(@"%@", [NSThread isMainThread]?@"Main":@"Not");
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
原文地址:https://www.cnblogs.com/lidongq/p/3967271.html