您的位置:首页 > 移动开发 > IOS开发

iOS 创建多线程的几种方法

2016-07-17 22:38 387 查看
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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: