通过GCD、NSOperationQueue队列、NSThread三种方法来创建多线程

#import "ViewController.h"



@interface ViewController ()

@property (weak, nonatomic) IBOutlet UILabel *remindLabel;



@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)sendBtnClick:(UIButton *)sender {



    /*--第一种采用GCD发送请求并刷新UI--*/

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        

        sleep(2);

        

        dispatch_async(dispatch_get_main_queue(), ^{

           

            _remindLabel.text=@"发送成功";

        });

       

    });

     /*--第二种采用NSBlockOperation、NSOperationQueue队列发送请求并刷新UI--*/

     NSOperationQueue *myQueue=[[NSOperationQueue alloc]init];

     NSBlockOperation *operation=[NSBlockOperation blockOperationWithBlock:^{

       //延时2秒

        sleep(2);

        //主线程刷新UI

        dispatch_async(dispatch_get_main_queue(), ^{

            

             _remindLabel.text=@"发送成功";

        });

    }];

    [myQueue addOperation:operation];

    

    

    /*--第三种采用NSThread发送请求并刷新UI--*/

    [NSThread detachNewThreadSelector:@selector(sendState) toTarget:self withObject:nil];

    

    

}

-(void)sendState

{

    sleep(2);

    dispatch_async(dispatch_get_main_queue(), ^{

        

        [self updateLabel];

    });

}

-(void)updateLabel

{

   _remindLabel.text=@"发送成功";

}

@end

通过GCD、NSOperationQueue队列、NSThread三种方法来创建多线程

你可能感兴趣的:(thread)