iOS中的多线程使用

iOS中的多线程方案如下:
这里写图片描述

1. NSThread

NSThread线程创建
/**
 * 创建线程的方式1
 */
- (void)createThread1
{
    // 创建线程
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:@"http://b.png"];
    thread.name = @"下载线程";

    // 启动线程(调用self的download方法)
    [thread start];
}

/**
 * 创建线程的方式2
 */
- (void)createThread2
{
    [NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"http://a.jpg"];
}

/**
 * 创建线程的方式3
 */
- (void)createThread3
{
    // 这2个不会创建线程,在当前线程中执行
    //    [self performSelector:@selector(download:) withObject:@"http://c.gif"];
    //    [self download:@"http://c.gif"];

    [self performSelectorInBackground:@selector(download:) withObject:@"http://c.gif"];
}
NSThread的类方法
[NSThread currentThread]
[NSThread mainThread]
NSThread线程状态
    // 睡眠5秒钟
    [NSThread sleepForTimeInterval:5];

    // 3秒后的时间
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:3];
    [NSThread sleepUntilDate:date];

    //线程退出
    for (int i = 0; i<100; i++) {
        NSLog(@"------%d", i);

        if (i == 49) {
            [NSThread exit];
        }
    }

2. GCD

后台异步并发队列(常用)
    // 获得全局的并发队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    // 将 任务 添加 全局队列 中去 异步 执行
    dispatch_async(queue, ^{
        NSLog(@"-----下载图片1---%@", [NSThread currentThread]);
    });
后台异步串行队列
    // 1.创建一个串行队列
    dispatch_queue_t queue = dispatch_queue_create("cn.heima.queue", NULL);

    // 2.将任务添加到串行队列中 异步 执行
    dispatch_async(queue, ^{
        NSLog(@"-----下载图片1---%@", [NSThread currentThread]);
    });
前台异步串行队列(常用)
    // 1.主队列(添加到主队列中的任务,都会自动放到主线程中去执行)
    dispatch_queue_t queue = dispatch_get_main_queue();

    // 2.添加 任务 到主队列中 异步 执行
    dispatch_async(queue, ^{
        NSLog(@"-----下载图片1---%@", [NSThread currentThread]);
    });
同步执行

使用dispatch_sync可以同步执行,即执行完block的内容,再往后执行

    dispatch_sync(queue, ^{
        NSLog(@"-----下载图片1---%@", [NSThread currentThread]);
    });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值