zoukankan      html  css  js  c++  java
  • IOS开发中多线程的使用

    一、创建多线程的五种方式

    1.开启线程的方法一

        NSThread * thread=[[NSThread alloc] initWithTarget:self selector:@selector(_update) object:nil];

    2.开启线程的方法二 

        [NSThread detachNewThreadSelector:@selector(_update) toTarget:self withObject:nil];

    3.开启线程的方法三

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

    4.开启线程的方法四

    复制代码
        NSOperationQueue *queue=[[NSOperationQueue alloc] init];
        [queue addOperationWithBlock:^{
            for(int i=0;i<50;i++){
                printf("子线程
    ");
            }
        }];
    复制代码

    5.开启线程的方法五

    复制代码
        //第一步开启线程池
            NSOperationQueue * queue=[[NSOperationQueue alloc] init];
        //设置并发数目
        [queue setMaxConcurrentOperationCount:2];
        
        //第二部创建多线程添加到线程池
        NSInvocationOperation * thread1=[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(_update1) object:nil];
        NSInvocationOperation *thread2=[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(_update2) object:nil];
        
        [thread1 setQueuePriority:NSOperationQueuePriorityVeryLow];
        [thread2 setQueuePriority:NSOperationQueuePriorityVeryHigh];
        
        [queue addOperation:thread1];
        [queue addOperation:thread2];
    复制代码
    二、多线程应用实例,加载图片。

    1.核心思想

      考虑到如果加载网络图片会延迟,在一个主线程加载会影响控件的渲染,此时可以采取多线程,异步加载完成后刷新UI。

    2.实现思路

      通过为UIImageView 增加类目来实现多线程下载。

      主要代码:

    复制代码
    #import "UIImageView+thread.h"
    
    @implementation UIImageView(load)
    
    
    - (void) setImageWithUrl:(NSString *)url{
        [self performSelectorInBackground:@selector(_loadImage:) withObject:url];
    
    
    }
    
    
    - (void) _loadImage:(NSString *)u{
    
        @autoreleasepool {
            
            NSURL *url=[NSURL URLWithString:u];
            NSData *data=[NSData dataWithContentsOfURL:url];
    
            UIImage *image=[UIImage imageWithData:data];
            
            [self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
            
        }
    }
  • 相关阅读:
    质量标准
    期权只是一张纸而已,但它的背后是心机
    Spring注解 @Resource和@Autowired
    Java7新语法 -try-with-resources
    Spring中Bean的命名问题及ref和idref之间的区别
    mybatis注解详解
    jquery ajax局部加载方法介绍
    SpringMVC批量上传
    【uploadify3.1使用二】批量文件、图片上传
    IE浏览器上传文件时本地路径变成”C:fakepath”的问题
  • 原文地址:https://www.cnblogs.com/tangshiguang/p/6753644.html
Copyright © 2011-2022 走看看