多线程的几种创建方法

  //创建线程的第一种方式
     NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@ "universe" ];
     [ thread start];
     [ thread release];
     
     
     //创建线程的第二种方式,NSThread类方法
     [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@ "yuzhou" ];
     
     
     //创建线程的第三种方法  NSObject方法
     [self performSelectorInBackground:@selector(run:) withObject:@ "nsobject thread" ];
     
     //创建线程的第四种方式
     NSOperationQueue *oprationQueue = [[NSOperationQueue alloc] init];
     [oprationQueue addOperationWithBlock:^{
         //这个block语句块在子线程中执行
         NSLog(@ "oprationQueue" );
     }];
     [oprationQueue release];
     
     //第五种创建线程的方式
     NSOperationQueue *oprationQueue1 = [[NSOperationQueue alloc] init];
     oprationQueue1.maxConcurrentOperationCount = 1; //指定池子的并发数
     
     //NSOperation 相当于java中的runnable接口,继承自它的就相当一个任务
     NSInvocationOperation *invation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run:) object:@ "invation" ];
     [oprationQueue1 addOperation:invation]; //将任务添加到池子里面,可以给池子添加多个任务,并且指定它的并发数
     [invation release];
     
     //第二个任务
     NSInvocationOperation *invation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run2:) object:@ "invocation2" ];
     invation2.queuePriority = NSOperationQueuePriorityHigh; //设置线程优先级
     [oprationQueue1 addOperation:invation2];
     [invation2 release];
     
     [oprationQueue1 release];
     
     //调用主线程,用来子线程和主线程交互,最后面的那个boolean参数,如果为yes就是等这个方法执行完了在执行后面的代码;如果为no的话,就是不管这个方法执行完了没有,接着往下走
     [self performSelectorOnMainThread:@selector(onMain) withObject:self waitUntilDone:YES];
     
     //---------------------GCD----------------------支持多核,高效率的多线程技术
     //创建多线程第六种方式
     dispatch_queue_t queue = dispatch_queue_create( "name" , NULL);
     //创建一个子线程
     dispatch_async(queue, ^{
         // 子线程code... ..
         NSLog(@ "GCD多线程" );
         
         //回到主线程
         dispatch_sync(dispatch_get_main_queue(), ^{ //其实这个也是在子线程中执行的,只是把它放到了主线程的队列中
             Boolean isMain = [NSThread isMainThread];
             if (isMain) {
                 NSLog(@ "GCD主线程" );
             }
         });
     });
     
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值