zoukankan      html  css  js  c++  java
  • 通过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

  • 相关阅读:
    java-引用数组、继承、super关键字
    java-分支重载以及构造方法
    java-面向对象之类、对象
    java-方法创建与使用
    java-数组排序之冒泡排序(经典排序)
    java-循环的应用环境以及数组的创建
    java-循环
    java-运算符与判断
    java-分支结构(四种基本分支结构的认识)
    java-运算符以及简单运用
  • 原文地址:https://www.cnblogs.com/thbbsky/p/4375961.html
Copyright © 2011-2022 走看看