iOS 创建多线程的几种方法

NSThread

  多线程方式1  实例方法

    NSThread *thread1 = [[NSThread alloc]initWithTarget:selfselector:@selector(threadAction1) object:nil];

    //启动线程  需要启动线程

    [thread1 start];


  多线程方式  2  类方法   不需要手动启动线程

    [NSThread detachNewThreadSelector:@selector(threadAction1) toTarget:selfwithObject:nil];

  多线程方式3

    [self performSelectorInBackground:@selector(threadAction1) withObject:nil];


  //回归主线程。更新ui

 

 1、   dispatch_sync(dispatch_get_main_queue(),block)


  2、  [self performSelectorOnMainThread:@selector(updateUI) withObject:selfwaitUntilDone:YES];


//多线程调用方法

-(void)threadAction1

{

     NSLog(@"子线程 === %@",[NSThread currentThread]);

    for (int i=0; i<50; i++)

    {

        NSLog(@"i === %d",i);

    }

    

    [self test1];这里调用tes1线程地址和 该线程地址相同

}

-(void)test1{

    NSLog(@"线程为  ======   %@",[NSThread currentThread]);

}

//    多线程方式4

    //创建一个操作队列

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

操作队列

  一、添加新线程  NSInvocationOperation *op1=[[NSInvocationOperationalloc]initWithTarget:self selector:@selector(op1Action) object:nil];

   添加到队列里面

     [opQueue addOperation:op1];


二、    用代码块的形式开辟一个新的线程

    [opQueue addOperationWithBlock:^{

            NSLog(@"4子线程=%@", [NSThread currentThread]);

    }];

-(void)op1Action

{

    NSLog(@"1子线程=%@", [NSThread currentThread]);

}



当多个线程同时访问同一资源的时候,注意线程同步问题
解决方案有三
一、设置线程同步锁,只能有一个线程来访问

   @synchronized(self) {

//执行操作 比如说取款

     

    }

二、创建一个串行队列

  dispatch_queue_t queue=dispatch_queue_create("test",NULL);

三、设置最大并发数

    //    设置最大并发数

  opQueue.maxConcurrentOperationCount=1;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值