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

来源:互联网 发布:java restaurant chef 编辑:程序博客网 时间:2024/05/24 06:40

本节要点:

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("多线程");              } );