ios线程的五种使用方式

  1. //第一种方式  手动创建并启动  
  2.    NSThread *t = [[NSThread alloc] initWithTarget:self selector:@selector(method) object:nil];  
  3.    [t start];  
  4.      
  5.    //第二种方式  类方法  
  6.    [NSThread detachNewThreadSelector:@selector(method) toTarget:self withObject:nil];  
  7.      
  8.    //第三种方式  类方法  
  9.    [self performSelectorInBackground:@selector(method) withObject:nil];  
  10.      
  11.    //第四种方式 block 语法  
  12.    NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];  
  13.    //会开启一个多线程,调用block  
  14.    [operationQueue addOperationWithBlock:^{  
  15.        for (int i=0; i<50; i++) {  
  16.            NSLog(@"多线程:%d", i);  
  17.        }  
  18.    }];  
  19.      
  20.    //第五种  线程队列(线程池)  
  21.    NSOperationQueue *operationQueue2 = [[NSOperationQueue alloc] init]; //相当于一个线程池,里面可以放很多线程,这个线程池管理多个线程的调度,可以给线程设置优先级,并发数  
  22.    operationQueue2.maxConcurrentOperationCount = 1;  //设置最大并发数量(并发=同时进行)  
  23.      
  24.    //创建线程  
  25.    NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(thread1) object:nil];  
  26.    //设置线程的优先级  
  27.    [operation1 setQueuePriority:NSOperationQueuePriorityVeryLow];  
  28.      
  29.    NSInvocationOperation *operation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(thread1) object:nil];  
  30.    [operation2 setQueuePriority:NSOperationQueuePriorityVeryHigh];  
  31.      
  32.    //将线程添加到线程池  
  33.    [operationQueue2 addOperation:operation1];  
  34.    [operationQueue2 addOperation:operation2];  
  35.      
  36.      
  37.    //----------------------回到主线程--------------------------------  
  38.      
  39.    //在多线程中可能加载数据,加载完了之后要刷新ui, ui必须在主线程上面操作,在多线程的方法中这样调用  
  40.    [self performSelectorOnMainThread:@selector(thread1) withObject:nil waitUntilDone:YES];  
  41.      
  42.      
  43.    //-----------------第六种线程的使用方式--------------  
  44.    //这个函数是C的函数,字符串test也要用C里面的字符串,是不带@符号的  
  45.    dispatch_queue_t queue = dispatch_queue_create("test", NULL);  
  46.    dispatch_async(queue, ^{  
  47.        for (int i=0; i<50; i++) {  
  48.            NSLog(@"多线程:%d", i);  
  49.        }  
  50.        //回到主线程执行  
  51.        dispatch_async(dispatch_get_main_queue(), ^{  
  52.            if ([NSThread isMainThread]) {  
  53.                NSLog(@"是主线程");  
  54.            }  
  55.        });  
  56.    });  

 

iOS代码   收藏代码
  1. -(void)thread1 {  
  2.     //这里是开启了一个新的线程,所以新的线程跟主线程脱离关系了,这个里面的内存管理,我们需要自己创建一个自动释放池  
  3.     //创建自动释放池  
  4.     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
  5.       
  6.     NSLog(@"执行多线程");  
  7.       
  8.     [pool release];  
  9. }  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值