首页 > 程序开发 > 移动开发 > Android >

[课堂实践与项目]IOS多线程之(3):Grand Central Dispatch(GCD)

2013-12-27

1 使用GCD进行线程处理 ----dispatch_async 使用,避免界面处理耗时的操作时候卡死,先进行线程操作,然后通知主线程更新界面 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORIT

//1.使用GCD进行线程处理  ----dispatch_async 使用,避免界面处理耗时的操作时候卡死,先进行线程操作,然后通知主线程更新界面

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
          //线程操作
        NSInteger row = [indexPath row];
        NSString *str = [self.array objectAtIndex:row];
        
        NSURL *url = [NSURL URLWithString:str];
        
        NSData *imageData = [NSData dataWithContentsOfURL:url];
        
        UIImage *image = [[UIImage alloc]initWithData:imageData];
        
        if (image != nil) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                cell.imageView.image = image;
                
                [cell.activityIndicatorView stopAnimating];
                
                //这里是不能用reloadData的,虽然更新了界面,但是你会发现很多的线程,导致app崩溃。
                //[self.tableView reloadData];
                //更新界面的操作
            });
        }
        
    
    });
     


2.

 //2 使用GCD进行线程处理      //dispatch_group_async可以监听一组事件是否完成,完成之后再通知执行其他的操作
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    
    
    __block UIImage *image;
    dispatch_group_async(group, queue, ^{
        NSInteger row = [indexPath row];
        NSString *str = [self.array objectAtIndex:row];
        
        NSURL *url = [NSURL URLWithString:str];
        
        NSData *imageData = [NSData dataWithContentsOfURL:url];
        
     image = [[UIImage alloc]initWithData:imageData];
        
        
    });
    //只有上面的操作完成之后,才能进行下面的更新操作。
    
    dispatch_group_notify(group, queue, ^{
    
        cell.imageView.image = image;
        
        [cell.activityIndicatorView stopAnimating];
    
    });
    
    

3.

    dispatch_queue_t queue = dispatch_queue_create(gcdtest.rongfzh.yc, DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        [NSThread sleepForTimeInterval:2];
        NSLog(@dispatch_async1);
    });
    dispatch_async(queue, ^{
        [NSThread sleepForTimeInterval:4];
        NSLog(@dispatch_async2);
    });
    dispatch_barrier_async(queue, ^{
        NSLog(@dispatch_barrier_async);
        [NSThread sleepForTimeInterval:4];

    });
    dispatch_async(queue, ^{
        [NSThread sleepForTimeInterval:1];
        NSLog(@dispatch_async3);
    });

2012-09-25 16:20:33.967 gcdTest[45547:11203] dispatch_async1

2012-09-25 16:20:35.967 gcdTest[45547:11303] dispatch_async2

2012-09-25 16:20:35.967 gcdTest[45547:11303] dispatch_barrier_async

2012-09-25 16:20:40.970 gcdTest[45547:11303] dispatch_async3


4.

4、dispatch_apply

执行某个代码片段N次。
dispatch_apply(5, globalQ, ^(size_t index) {
// 执行5次
});

相关文章
最新文章
热点推荐