码迷,mamicode.com
首页 > 编程语言 > 详细

多线程和GCD的使用

时间:2015-09-22 14:57:06      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

1.NSThread的使用

方式一:开启多线程,并且执行方法threadAction

[self performSelectorInBackGround:@selector(threadAction) withObject:nil];


方式二:

NSThread *thread =[[NSThread alloc]initWithTarget:self  selector:@selector(threadAction:) object:@"text"]
thread.name = @"thread1";
//开启线程
[thread start];

方式三:开启新的线程,并且执行

[NSThread decathNewThreadSelector:@selector(threadAction) toTarget:self withObject:@"哈哈"];



- (void)threadAction:(NSString *)str {
   //1.获取当前线程对象
    NSThread *thread = [NSThread currentThread];
    NSLog(@"thread:%@",thread);
    
    //2.判断当前是否是在多线程
    if ([NSThread isMultiThreaded]) {
        NSLog(@"当前是否是多线程");
    }
    
    for (int i=0; i<50; i++) {
        NSLog(@"thread:%d",i);
        
        if (i == 10) {
            //让当前线程睡眠3秒
//            [NSThread sleepForTimeInterval:3];
            
            //退出当前线程
//            [NSThread exit];
        }
        
    }    
    //回到主线程
//   [self performSelectorOnMainThread:<#(SEL)#> withObject:<#(id)#> waitUntilDone:<#(BOOL)#>]
}

2.NSOperationQueue的使用

//创建线程队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];

//关闭暂停队列
[queue setSuspend: YES];
//设置最大并发数
queue.maxConcurrentOperationCount = 1;

//创建线程
NSInvocationOperation *operation1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(thread1:) object:@"op1"];
NSInvocationOperation *operation2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(thread1:) object:@"op2"];

//设置线程的优先级
operation1.queuePriority = NSOperationQueuePriorityNormal;
operation1.queuePriority = NSOperationQueuePriorityHigh;
//将线程添加到队列中
[queue addOperation:operation1];
[queue addOperation:operation2];


//直接用block
[queue addOperationWithBlock:^{

@autoreleasepool {
   for (int i = 0; i < 50; i ++)
       {
          NSLog(@"op3:%d",i);

       }

   }
}];

//开始队列
[queue setSuspended:NO];

- (void)thread1:(NSString *)threadName {

    @autoreleasepool {
        for (int i=0; i<50; i++) {
            NSLog(@"thread1:%d",i);
        }
        
    }
    
}

- (void)thread2:(NSString *)threadName {
    
    @autoreleasepool {
        
        for (int i=0; i<50; i++) {
            NSLog(@"thread2:%d",i);
        }
        
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
        
        //如果设置定时器,必须设置runLoop,线程二则不会关闭;
//        [[NSRunLoop currentRunLoop] run];
        
    }
    
}

- (void)timeAction {

    NSLog(@"timeAction");
    
}

3.GCD的使用

一:队列

 

  •  串行队列:添加到队列中的任务是一个一个执行的

  •  并行(发)队列:添加到队列中的任务是多个同时执行的 

  •  主队列:里面的任务都是在主线程执行的,可以理解为主队列就是串行队列的一种 

  •  全局队列:并行(发)队列

 

 二:同步、异步

  •   同步:需要后面的任务等待,不会开启新的线程,会直接使用当前的线程

  •  异步:不需要后面的任务等待,会开启新的线程

1.创建并发队列

    优先级:

     DISPATCH_QUEUE_PRIORITY_HIGH

     DISPATCH_QUEUE_PRIORITY_DEFAULT

     DISPATCH_QUEUE_PRIORITY_LOW

     DISPATCH_QUEUE_PRIORITY_BACKGROUND

     

    //1.创建并行队列
  //    dispatch_queue_t queue1 = dispatch_queue_create("queue1", DISPATCH_QUEUE_CONCURRENT);
    
    //2.获取全局队列(并行队列)
       dispatch_queue_t queue2 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

   1.1向并发队列中添加任务

<1>异步添加任务

    dispatch_async(queue2, ^{
        @autoreleasepool {
            
            for (int i=0; i<50; i++) {
                NSLog(@"1....i:%d",i);
            }
        }
    });
    
    for (int i=0; i<50; i++) {
        NSLog(@"??....i:%d",i);
    }
    
    dispatch_async(queue2, ^{
            
            for (int i=0; i<50; i++) {
                NSLog(@"2....i:%d",i);
            }
    });

<2>同步添加任务

    dispatch_sync(queue2, ^{
        
        for (int i=0; i<50; i++) {
            NSLog(@"??....i:%d",i);
        }
    });
    
    for (int i=0; i<50; i++) {
        NSLog(@"??....i:%d",i);
    }
    
    dispatch_sync(queue2, ^{
        for (int i=0; i<50; i++) {
            NSLog(@"??....i:%d",i);
        }
    });

2.创建串行队列

dispatch_queue_t queue = dispatch_queue_create("queue3", DISPATCH_QUEUE_SERIAL);

   1.1向串行队列中添加任务

<1>异步添加

    dispatch_async(queue, ^{
        for (int i=0; i<50; i++) {
            NSLog(@"??....i:%d",i);
        }
    });
    
    dispatch_async(queue, ^{
        for (int i=0; i<50; i++) {
            NSLog(@"??....i:%d",i);
        }
    });
    
    for (int i=0; i<100; i++) {
        NSLog(@"??...--------.i:%d",i);
    }

<2>同步添加任务

    dispatch_sync(queue, ^{
        for (int i=0; i<50; i++) {
            NSLog(@"??....i:%d",i);
        }
    });
    
    dispatch_sync(queue, ^{
        for (int i=0; i<50; i++) {
            NSLog(@"??....i:%d",i);
        }
    });
    
    for (int i=0; i<100; i++) {
        NSLog(@"??...--------.i:%d",i);
    }

3.创建主队列(在使用主队列的时候,绝对不可以在主队列中同步添加任务

    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    
    
    //向刚才创建的并发队列中异步添加一个网络加载的任务,加载完成后,回到主线程操作UI
    dispatch_async(queue2, ^{
        NSLog(@"网络加载");
        
        //完成了
        dispatch_async(mainQueue, ^{
            NSLog(@"操作UI");
        });
        
        
    });








多线程和GCD的使用

标签:

原文地址:http://my.oschina.net/zhangqy/blog/509582

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!