【无限互联】iOS开发之多线程开发

本节要点:

1.多线程的概念

2.掌握iOS中多线程的多种创建方式


多线程的概念

每个进程是一个应用程序,都有独立的内存空间

一个进程中的线程共享其进程中的内存和资源

使用多线程技术,提高CPU的使用率,防止主线程堵塞。 

多个线程可以提高应用程序在多核系统上的实时性能

每个程序都有⼀一个主线程,程序启动时,创建主线程,调用main函数来启动程序。

主线程的生命周期和程序是绑定的,程序结束时,主线程停止。

任何有可能堵塞的任务不要在主线程执行,主线程不流畅会导致程序界面的不流畅。(:网络访问、大文件写入磁盘、

清理缓存,等等)


多线程的创建和启动

第1种方式
NSThread *t = [[NSThread alloc] initWithTarget:self selector:@selector(mutableThread) object:nil];
[t start];

第2种方式
[NSThread detachNewThreadSelector:@selector(mutableThread) toTarget:self withObject:nil];

第3种方式
[self performSelectorInBackground:@selector(mutableThread) withObject:nil];

第4种block语法开启一个线程
NSOperationQueue *threadQueue = [[NSOperationQueue alloc] init]; [threadQueue addOperationWithBlock:^(void) {
        NSThread *t = [NSThread currentThread];
        if (![t isMainThread]) {
              NSLog(@"是多线程"); 
       }
}];

第5种方式线程池
NSOperationQueue *threadQueue = [[NSOperationQueue alloc] init]; NSInvocationOperation *op = [[NSInvocationOperation alloc]
                                 initWithTarget:self
                               selector:@selector(mutableThread) object:nil];
    [threadQueue addOperation:op];

第6种方式GCD,适用于多核开发
dispatch_queue_t network_queue;    
    
network_queue = dispatch_queue_create("com.myapp.network", nill);   

dispatch_async(network_queue, ^{      
    UIImage *cellImage = [self loadMyImageFromNetwork:image_url];      
    NSLog("多线程");    
          
} ); 






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值