多線程(NSThread、NSOperation、NSInvocationOperation)

  • 使用Thread 的類方法detachNewThreadSelector創(chuàng)建線程
- (void)viewDidLoad
{
    // 調(diào)用類方法的新線程 立即開始執(zhí)行
    // [NSThread detachNewThreadSelector:@selector(doIt) toTarget:self withObject:nil];
    NSThread *thd = [[NSThread alloc] initWithTarget:self selector:@selector(doIt) object:nil];
    // 線程優(yōu)先級
    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];
}

  • 調(diào)用實例方法 start
- (void)viewDidLoad
{
    // 調(diào)用類方法的新線程 立即開始執(zhí)行
    NSThread *thd = [[NSThread alloc] initWithTarget:self selector:@selector(doIt) object:nil];
    // 線程優(yōu)先級
    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
{
    //創(chuàng)建操作隊列
    NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
    //設(shè)置隊列中最大的操作數(shù)
    [operationQueue setMaxConcurrentOperationCount:1];
    //創(chuàng)建操作(最后的object參數(shù)是傳遞給selector方法的參數(shù))
    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子類來創(chuàng)建線程

@implementation MyTaskOperation  
  
//相當(dāng)于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]; 
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容