iOS多线程——郭挺

线程的概念

附:多线程用于运行一些在主线程无法运行的任务,比如下载或者加载图片,如果放到主线程来运行会将主线程堵死,从而无法响应。

每个正在系统上运行的程序都是一个进程。每个进程包含一到多个线程。进程也可能是整个程序或者是部分程序的动态执行。线程是一组指令的集合,或者是程序的特殊段,它可以在程序里独立执行。也可以把它理解为代码运行的上下文。所以线程基本上是轻量级的进程,它负责在单个程序里执行多任务。通常由操作系统负责多个线程的调度和执行。
线程是程序中一个单一的顺序控制流程.在单个程序中同时运行多个线程完成不同的工作,称为多线程.

进程和线程的区别:
线程和进程的区别在于,子进程和父进程有不同的代码和数据空间,而多个线程则共享数据空间,每个线程有自己的执行堆栈和程序计数器为其执行上下文.多线程主要是为了节约CPU时间,发挥利用,根据具体情况而定. 线程的运行中需要使用计算机的内存资源和CPU。

开启多线程的6种方式:(GCD为高效的创建方式)

//------1.第一种方式:创建一个多线程对象
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(mutableThread:) object:nil];
//开启多线程(开启之后主线程继续往下执行,和多线程并发执行)
[thread start];
 */
//------2.第二种方式
//[NSThread detachNewThreadSelector:@selector(mutableThread:) toTarget:self withObject:nil];

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

//------4.第四种方式
NSOperationQueue *threadQueue = [[NSOperationQueue alloc] init];
[threadQueue addOperationWithBlock:^{
    NSThread *t = [NSThread currentThread];
    if (![t isMainThread]) {
        NSLog(@"多线程!");
        for (int i = 0; i<100; i++) {
            NSLog(@"--多线程--%d",i);
        }
    }
}];

//------5.第五种方式
//创建一个线程队列
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
//设置线程执行的最大并发数
operationQueue.maxConcurrentOperationCount = 1;
//创建一个线程操作对象
NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(mutableThread1:) object:nil];
//创建一个线程操作对象
NSInvocationOperation *operation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(mutableThread2:) object:nil];
//设置线程的优先级(此处设置无效!!!!!!!!!!!!!!!!!!!!!!!!)
operation2.queuePriority = NSOperationQueuePriorityVeryHigh;
//将线程添加到队列中, 若有超出最大并发执行数,则先添加哪个,哪个先执行
[operationQueue addOperation:operation1];
[operationQueue addOperation:operation2];


//------6.第六种方式:GCD
//创建一个队列
//NSMutableString *label = [NSMutableString stringWithString:@"label"];
dispatch_queue_t queue = dispatch_queue_create("label", NULL);//注意!!!!!!这里的字符串是C类型,前面不应有@符号!!!!
dispatch_async(queue, ^{
    for (int i = 0; i<100; i++) {
        NSLog(@"--多线程q--%d",i);
    }
    //判断是否为多线程(此处无法判断!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!)
    if ([NSThread isMultiThreaded]) {
        NSLog(@"isMultiThreaded");
    }
    //NSLog(@"isMultiThreaded");
    dispatch_sync(dispatch_get_main_queue(), ^{
        //判断是否为主线程
        if ([NSThread isMainThread]) {
            NSLog(@"isMainThread");
        }

    });
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值