多线程(NSThread、NSOperation、NSInvocationOperation)

  • 使用Thread 的类方法detachNewThreadSelector创建线程
- (void)viewDidLoad
{
    // 调用类方法的新线程 立即开始执行
    // [NSThread detachNewThreadSelector:@selector(doIt) toTarget:self withObject:nil];
    NSThread *thd = [[NSThread alloc] initWithTarget:self selector:@selector(doIt) object:nil];
    // 线程优先级
    thd.threadPriority = 10;
    [thd start];
    
}

-(void)doIt{

    UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://pic14.nipic.com/20110522/7411759_164157418126_2.jpg"]]];
    
    UIImageView *imgv = [[UIImageView alloc] initWithImage:img];
    [self.view addSubview:imgv];
}

  • 调用实例方法 start
- (void)viewDidLoad
{
    // 调用类方法的新线程 立即开始执行
    NSThread *thd = [[NSThread alloc] initWithTarget:self selector:@selector(doIt) object:nil];
    // 线程优先级
    thd.threadPriority = 10;
    [thd start];
}

-(void)doIt{

    UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://pic14.nipic.com/20110522/7411759_164157418126_2.jpg"]]];
    
    UIImageView *imgv = [[UIImageView alloc] initWithImage:img];
    [self.view addSubview:imgv];
}

NSOperationQueue

- (void)viewDidLoad
{
    //创建操作队列
    NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
    //设置队列中最大的操作数
    [operationQueue setMaxConcurrentOperationCount:1];
    //创建操作(最后的object参数是传递给selector方法的参数)
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doIt) object:nil];
    //将操作添加到操作队列
    [operationQueue addOperation:operation];
    
}

-(void)doIt{

    UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://pic14.nipic.com/20110522/7411759_164157418126_2.jpg"]]];
    
    UIImageView *imgv = [[UIImageView alloc] initWithImage:img];
    [self.view addSubview:imgv];
}

  • 使用NSOperation子类来创建线程

@implementation MyTaskOperation  
  
//相当于Java线程中的run方法  
-(void)main  
{  
    //do someting...  
    NSLog(@"Thread is running...");  
    [NSThreadsleepForTimeInterval:3];  
    NSLog(@"Thread is done...");  
}  
@end 


使用方法
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];  
MyTaskOperation *myTask = [[MyTaskOperation alloc] init];  
[operationQueue addOperation:myTask];  
[myTask release];  
[operationQueue release]; 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容