iOS UI21_多线程

//
//  MyOperation.m
//  UI21_多线程
//
//  Created by dllo on 15/8/26.
//  Copyright (c) 2015年 zhozhicheng. All rights reserved.
//

#import "MyOperation.h"

@implementation MyOperation

-(void)main
{
    NSInteger count = 1;
    for (NSInteger i = 0; i<600000000; i++) {
        count ++;
    }
    NSLog(@"%ld",count);
}
@end
//
//  ViewController.m
//  UI21_多线程
//
//  Created by dllo on 15/8/26.
//  Copyright (c) 2015年 zhozhicheng. All rights reserved.
//

#import "ViewController.h"
#import "MyOperation.h"
#import "MBProgressHUD.h"
#import "AFNetworking.h"

@interface ViewController ()
@property(nonatomic,retain)UIButton *button;
@property(nonatomic,retain)UIImageView *imageView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.button = [UIButton buttonWithType:UIButtonTypeSystem];
    self.button.frame = CGRectMake(100, 100, 150, 50);
    [self.button setTitle:@"测试" forState:UIControlStateNormal];
    self.button.layer.borderWidth = 1;
    self.button.layer.cornerRadius = 10;
    [self.view addSubview:self.button];
    [self.button addTarget:self action:@selector(GCDAction:) forControlEvents:UIControlEventTouchUpInside];

    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 200, 150, 150)];
    self.imageView.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:self.imageView];
    [_imageView release];

    NSURL *url = [NSURL URLWithString:@"http://img4.duitang.com/uploads/item/201207/28/20120728105310_jvAjW.thumb.600_0.jpeg"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image = [UIImage imageWithData:data];
    self.imageView.image =image;


//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    hud.labelText = @"正在下载.....";
    //设置样式
//    hud.mode = MBProgressHUDModeDeterminate;
    //创建一个请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://help.adobe.com/archive/en/photoshop/cs6/photoshop_reference.pdf"]];
    AFHTTPRequestOperation *
    operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    //指定一个文件的保存路径,放到沙河的caches文件里
    NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachesPath =sandBox[0];
    //拼接文件路径
    NSString *pdfPath = [cachesPath stringByAppendingPathComponent:@"test.pdf"];
    NSLog(@"%@",pdfPath);
    //把文件下载到指定的文件夹路径内,写成相应的文件名
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:pdfPath append:NO];
    //通过AF进行下载
    //这是下载进度的一个block,里面会返回当前的下载进度,在这个block里设置hud的进度显示
//    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
//        hud.progress = (1.0) * (totalBytesRead) / totalBytesExpectedToRead;
//    }];
    //当下载结束之后,控制进度的hud应该消失,所以我们通过af进行下载完成的进度判断
//    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSLog(@"下载成功");
//        //移除hud
//        [hud removeFromSuperview];
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"%@",error);
//        [hud removeFromSuperview];
//    }];
    //把任务添加到队列里
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation:operation];
}
-(void)click:(UIButton *)button
{
   //线程卡死
    NSInteger count = 0;
    for (NSInteger i = 0; i<100000; i++) {
        count++;
        NSLog(@"%ld",count);
    }
    NSLog(@"%ld",count);
}
#pragma mark 第一种解决线程问题的方法 NSObject提供的方法
-(void)NSObjectThread:(UIButton *)button
{
    [self performSelectorInBackground:@selector(click:) withObject:button];
    //优点:写法特别简单,能快速开辟一个临时的线程
    //缺点:不能保证线程使用时候的数据安全

}
#pragma mark 第二种方式 NSThread
-(void)NSTHreadAction:(UIButton *)button
{
    //NSThread本身就是一个线程类,他可以控制线程休眠或者创建
    //当前的主线程
    NSLog(@"%@",[NSThread currentThread]);
    //主线程休眠三秒
    [NSThread sleepForTimeInterval:3];
    NSLog(@"111111");
    //如果用NSThread创建对象,创建出来的就是新的线程
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(click:) object:nil];
    //可以给新的线程对象起名
    thread.name = @"zhangyangyang";
    //启动子线程
    [thread start];
    //优点:可以直接通过创建方式来控制线程
    //缺点:什么都需要手动设置,包括名,开始,太麻烦
}
#pragma mark 第三种 NSOperation 任务
-(void)operationAtion:(UIButton *)button
{
//    NSOperation是一个抽象类,如果想使用这个抽象类,必须要创建一个他的子类

    MyOperation *operation = [[MyOperation alloc] init];
    [operation start];
    //他不能单独拿出来使用,如果单独使用和之前不考虑线程方式是一样的会卡死主线程,他一般和MyOperationQueue配合使用

}
-(void)operationQueue:(UIButton *)button
{
    //默认和任务一起配合使用解决多线程问题

    //队列:队列中通过一个线程池来管理所有闲置的线程,这样可以提高线程的重用利用率,避免重复创建线程,整合资源
    //优点:内部不需要关心线程的安全问题,用起来相对简单
    //缺点:效率稍微有点低

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    //设置最大并发数
    [queue setMaxConcurrentOperationCount:2];
    MyOperation *op1 = [[MyOperation alloc] init];
    MyOperation *op2 = [[MyOperation alloc] init];
    MyOperation *op3 = [[MyOperation alloc] init];
    MyOperation *op4 = [[MyOperation alloc] init];
    MyOperation *op5 = [[MyOperation alloc] init];
    //把任务加到队列
    [queue addOperation:op1];
    [queue addOperation:op2];
    [queue addOperation:op3];
    [queue addOperation:op4];
    [queue addOperation:op5];

}
-(void)GCDAction:(UIButton *)button
{
//    //GCD是苹果提供的一种处理多线程的解决方案,整体比较好,和operationQueue两种是常见的解决线程问题的方法
//    //这个方法可以保证无论哪个线程执行都只执行一次
//    static dispatch_once_t oneToKen;
//    dispatch_once(&oneToKen, ^{
//        
//    });
//    //自定义一个队列
//    //第一个参数:给队列起一个名(C语言字符串,不加@)  第二个参数:设置队列并行
//    //DISPATCH_QUEUE_CONCURRENT并行队列
//    dispatch_queue_t myQueue = dispatch_queue_create("zhangyangyang", DISPATCH_QUEUE_CONCURRENT);
//    //接下来,可以在队列执行一些任务
//    dispatch_async(myQueue, ^{
//        NSInteger count = 0;
//        for (NSInteger i = 0; i<60000; i++) {
//            count++;
//        }
//        NSLog(@"%ld",count);
//    });

   
    //网络请求一般会在子线程里进行加载,但是显示这个数据都在主线程里进行,所以需要把请求的数据放到主线程使用
    //定义一个全局的队列
    //第一个参数:设置当前队列优先
    //第二个参数:没有实际含义,留给以后用
    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //再获取一下当前的主队列,也就是主线程
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    //通过异步进行数据请求
    dispatch_async(globalQueue, ^{
        //通过网址请求图片数据
        NSString *picStr = @"http://img4.duitang.com/uploads/item/201207/28/20120728105310_jvAjW.thumb.600_0.jpeg";
        NSURL *url =[NSURL URLWithString:picStr];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        //把请求下来的数据到主线程进行刷新
        dispatch_async(mainQueue, ^{
            self.imageView.image = image;
        });

    });



}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值