IOS开发 网络与多线程

线程的创建

 

线程的创建与启动

// 1. 第⼀种开启新的线程调⽤用 mutableThread
NSThread *t = [[NSThread alloc] initWithTarget:self object:nil];
[t start]; // 需要⼿手动开启
// 2. 第⼆种开启新的线程调⽤用 mutableThread
[NSThread detachNewThreadSelector:@selector(mutableThread) toTarget:self withObject:nil];
// 3. 第三种开启新的线程调⽤用 mutableThread
[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.NSOperation开启⼀一个线程
NSOperationQueue *threadQueue = [[NSOperationQueue alloc] init]; 
NSInvocationOperation *op = [[NSInvocationOperation alloc] object:nil];
[threadQueue addOperation:op];
// 在主线程上调⽤用 reloadData 方法
[self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];

 

多线程的常用方法

NSThread的常用方法

// 判断当前线程是否是多线程
+ (BOOL)isMultiThreaded;
// 获取当前线程对象
+ (NSThread *)currentThread;
// 使当前线程睡眠指定的时间,单位为秒
+ (void)sleepForTimeInterval:(NSTimeInterval)ti; 
// 退出当前线程 + (void)exit; // 判断当前线程是否为主线程 + (BOOL)isMainThread // 启动该线程 - (void)start

 

GCD

GCD(Grand Central Dispatch)是一个大的主题。它可以提高代码的执行效率与多 核的利用率。

// 创建⼀一个队列
dispatch_queue_t queue = dispatch_queue_create("test", NULL); 
// 创建异步线程 dispatch_async(queue, ^{ // 多线程 // 回到主线程执⾏行 dispatch_sync(dispatch_get_main_queue(), ^{ // 主线程 }); });

 

自动释放池

子线程的内存管理

新创建的子线程需要添加自动释放池管理内存

// 创建⼦子线程
[self performSelectorInBackground:@selector(mutableThread) withObject:nil];
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    for (int i=0; i<10; i++) {
        NSLog(@"%d",i);
        [NSThread sleepForTimeInterval:1];
    }
    [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
    [pool release];
}

 

NSRunLoop的基本概念

Run loops 是线程相关的的基础框架的一部分。

一个 run loop 就是一个事件处理 的循环,用来不停的调度工作以及处理输入事件。

线程的生命周期存在五个状态:新建、就绪、运行、阻塞、死亡

NSRunLoop可以保持一个线程一直为活动状态,不会马上销毁掉。

定时器在多线程的使用

在多线程中使用定时器必须开启Runloop,因为只有开启Runloop保持线程为活动 状态,才能保持定时器能不断执行。

示例:

- (void)runThread {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAction) userInfo:nil // 开启Runloop来使线程保持存活状态
    [[NSRunLoop currentRunLoop] run];
    [pool release];
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted on 2014-10-20 10:06  rwpnyn  阅读(170)  评论(1编辑  收藏  举报

导航