首页 > 其他分享 >iOS 多线程复习

iOS 多线程复习

时间:2024-01-25 14:57:35浏览次数:20  
标签:--- 复习 currentThread iOS NSLog dispatch queue NSThread 多线程

iOS中的线程主要有四种:1.pThread 2.NSThread 3.GCD 4.NSOpreaction

基础知识:
线程、任务和队列的概念:

 

异步、同步 & 并行、串行的特点:

组合特点:

 

 

1.pThread

  C语言所写,面向过程,使用较少.

oc:

#pragma Mark - pThread
- (void)pThreadDemo{
    pthread_t pthread;
    pthread_create(&pthread,NULL,run,NULL);
}

void *run(void *data){
    for (int i = 0; i < 10; i++) {
        NSLog(@"%d",i);
        sleep(1);
    }
    return NULL;
}  

Swift:

    //pThread
    func pThreadDemo() {
        var thread: pthread_t? = nil
        pthread_create(&thread, nil, { (_) -> UnsafeMutableRawPointer? in
            for var i in 0...10{
                print("\(i)")
                sleep(1)
            }
            return nil;
        }, nil)
        
    } 

2.NSThread  

苹果封装后的,面向对象

NSThread有name,threadPriority两个属性,一个设置当前线程的名字,一个设置当前线程的优先级(0-1).

它有3种创建方式.其中第三种performSelector有很多方法:

 在当前线程中执行一个方法:

    [self performSelector:<#(SEL)#>];

在当前线程中执行一个方法并传参:

[self performSelector:<#(SEL)#> withObject:<#(id)#>];

 

在当前程中延迟几秒执行一个方法并传参:

[self performSelector:<#(nonnull SEL)#> withObject:<#(nullable id)#> afterDelay:<#(NSTimeInterval)#> ]

在主线程中执行一个方法并传参:

[self performSelectorOnMainThread:<#(nonnull SEL)#> withObject:<#(nullable id)#> waitUntilDone:<#(BOOL)#>];

在后台(子线程)中执行一个方法并传参:

 [self performSelectorInBackground:<#(nonnull SEL)#> withObject:<#(nullable id)#>];

等等.下面代码会举例说明.

其中,线程锁也很常见,如卖票系统:

    @synchronized(self){
        ...
    }

或者

@property (nonatomic,strong) NSCondition * condition;


   [self.condition lock];
      ...
   [self.condition unlock];

  

OC:

#pragma Mark - NSThreadDemo
- (void)NSThreadDemo{
//    1.通过alloc init 创建
        NSThread * t1 = [[NSThread alloc]initWithTarget:self selector:@selector(nsThreadRun) object:nil];
        [t1 setName: @"我是名字"];    //为线程设置的名字
        [t1 setThreadPriority:0.5];   //设置优先级  0-1
        [t1 start];

//    2.通过detachNewThreadSelector
        [NSThread detachNewThreadSelector:@selector(nsThreadRun) toTarget:self withObject:nil];
        [NSThread detachNewThreadWithBlock:^{
            NSLog(@"%@",[NSThread currentThread].isMainThread == YES ? @"主线程" : @"子线程");
        }];
    
//    3.通过 performSelector
    [self performSelectorInBackground:@selector(nsThreadRun) withObject:nil];
    
}

-(void)nsThreadRun{
NSLog(@"%@",[NSThread currentThread].isMainThread == YES ? @"主线程" : @"子线程");
    for (int i = 0; i < 10; i++) {
        NSLog(@"%d",i);
        sleep(1);
    }
}

 Swift:

    //NSThread
    func nsThreadDemo(){
        //1.通过init创建
        let thread:Thread = Thread.init(target: self, selector: #selector(nsThreadRun), object: nil)
        thread.name = "我是线程"
        thread.threadPriority = 0.4
        thread.start()
        
        //2.detachNewThreadSelector
       Thread.detachNewThreadSelector(#selector(nsThreadRun), toTarget: self, with: nil)
        Thread.detachNewThread {
            print("\(Thread.current.isMainThread)")
        }
        
        //3.performSelector
        self .performSelector(inBackground: #selector(nsThreadRun), with: nil)
        
    }

    @objc func nsThreadRun(){
        print("当前线程是:\(Thread.current.isMainThread ? "主":"子")")
        for var i in 0...10{
            print("\(i)")
            sleep(1)
        }
    }

3.GCD 

使用最多,虽然也是C语言所写,但是加入了block,使用起来更加灵活.

 OC:

 

(1):异步执行 + 并行队列

//创建一个并行队列
    dispatch_queue_t queue = dispatch_queue_create("标识符", DISPATCH_QUEUE_CONCURRENT);
    
    NSLog(@"---start---");
    
    //使用异步函数封装三个任务
    dispatch_async(queue, ^{
        NSLog(@"任务1---%@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"任务2---%@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"任务3---%@", [NSThread currentThread]);
    });
    
    NSLog(@"---end---");

 

(2):异步执行 + 串行队列

//创建一个串行队列
    dispatch_queue_t queue = dispatch_queue_create("标识符", DISPATCH_QUEUE_SERIAL);
    
    NSLog(@"---start---");
    //使用异步函数封装三个任务
    dispatch_async(queue, ^{
        NSLog(@"任务1---%@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"任务2---%@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"任务3---%@", [NSThread currentThread]);
    });
    NSLog(@"---end---");

(3):同步执行 + 并行队列

//创建一个并行队列
 dispatch_queue_t queue = dispatch_queue_create("标识符", DISPATCH_QUEUE_CONCURRENT);
    
    NSLog(@"---start---");
    //使用同步函数封装三个任务
    dispatch_sync(queue, ^{
        NSLog(@"任务1---%@", [NSThread currentThread]);
    });
    dispatch_sync(queue, ^{
        NSLog(@"任务2---%@", [NSThread currentThread]);
    });
    dispatch_sync(queue, ^{
        NSLog(@"任务3---%@", [NSThread currentThread]);
    });
    NSLog(@"---end---");

  

(4)同步执行+ 串行队列

 

    //创建一个串行队列
    dispatch_queue_t queue = dispatch_queue_create("标识符", DISPATCH_QUEUE_SERIAL);
    
    NSLog(@"---start---");
    //使用异步函数封装三个任务
    dispatch_sync(queue, ^{
        NSLog(@"任务1---%@", [NSThread currentThread]);
    });
    dispatch_sync(queue, ^{
        NSLog(@"任务2---%@", [NSThread currentThread]);
    });
    dispatch_sync(queue, ^{
        NSLog(@"任务3---%@", [NSThread currentThread]);
    });
    NSLog(@"---end---");

 

  

(5)异步执行+主队列

    //获取主队列
    dispatch_queue_t queue = dispatch_get_main_queue();
    
    NSLog(@"---start---");
    //使用异步函数封装三个任务
    dispatch_async(queue, ^{
        NSLog(@"任务1---%@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"任务2---%@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"任务3---%@", [NSThread currentThread]);
    });
    NSLog(@"---end---");

  

(6)同步执行+主队列(死锁)

 

//获取主队列
    dispatch_queue_t queue = dispatch_get_main_queue();
    
    NSLog(@"---start---");
    //使用同步函数封装三个任务
    dispatch_sync(queue, ^{
        NSLog(@"任务1---%@", [NSThread currentThread]);
    });
    dispatch_sync(queue, ^{
        NSLog(@"任务2---%@", [NSThread currentThread]);
    });
    dispatch_sync(queue, ^{
        NSLog(@"任务3---%@", [NSThread currentThread]);
    });
    NSLog(@"---end---");

  

 

 

标签:---,复习,currentThread,iOS,NSLog,dispatch,queue,NSThread,多线程
From: https://www.cnblogs.com/shaoting/p/8467843.html

相关文章

  • GDB调试之多线程死锁调试(二十四)
    调试代码如下所示:#include<thread>#include<iostream>#include<vector>#include<mutex>usingnamespacestd;mutex_mutex1;mutex_mutex2;intdata1;intdata2;intdo_work_1(){ std::cout<<"线程函数do_work_1开始"<<......
  • 【精品教程】如何查看iOS崩溃日志
    简介当一个应用程序崩溃,会产生一个崩溃报告(crashreport),并存储到设备中。崩溃报告描述了应用程序崩溃的条件,通常包含每个执行线程的完整回溯。查看崩溃报告可以帮助我们了解应用程序的崩溃情况,并尝试修复问题。符号化崩溃报告崩溃报告需要进行符号化(symbolicated),才能够进行分析......
  • rust使用lazy_static对全局变量多线程并发读写示例
    首先需要在项目依赖Cargo.toml添加lazy_static依赖项[dependencies]lazy_static="1.4.0"示例代码如下:uselazy_static::lazy_static;usestd::sync::{RwLock,RwLockReadGuard,RwLockWriteGuard};usestd::thread;#[derive(Debug)]structSharedData{data:Vec<......
  • jmeter读取csv文件控制多线程不重复读取
    在Jmeter中设置并发为S,循环次数为N时,参数化文件可能被重复读取N次,无法保证每次读取的数据均不一样,此处介绍保证数据不重复的方法。在线程组下添加一个CSVDataSetConfig,具体配置如下图:将配置中默认:RecycleonEOF=True,StopthreadonEOF=False修改为:RecycleonEO......
  • 2024-1-25axios错误处理
    目录axios错误处理axios错误处理该错误是当时在POST案例出现的,当提交过一次用户后再次提交出现了报错。场景:再次注册相同的账号,会遇到错误信息处理:用更直观的方式,给普通用户展示错误信息错误处理固定格式语法:在then方法的后面,通过点语法调用catch方法,传入回调函数error并定......
  • Java 多线程交替打印
    目录题目方案一:synchronized方法二:ReentrantLock方法三:ReentrantLock+Condition(非公平锁)方法四:ReentrantLock+Condition(公平锁)方法五:Semaphore题目使用三个线程T1、T2、T3,如何让他们按顺序交替打印10次ABC。方案一:synchronizedpublicclassSynchronizedLockPrint......
  • 支付宝:多线程事务怎么回滚?说用 @Transactional 可以回去等通知了!
    1,最近有一个大数据量插入的操作入库的业务场景,需要先做一些其他修改操作,然后在执行插入操作,由于插入数据可能会很多,用到多线程去拆分数据并行处理来提高响应时间,如果有一个线程执行失败,则全部回滚。2,在spring中可以使用@Transactional注解去控制事务,使出现异常时会进行回滚,在多线程......
  • iOS 多级页面之间的代理方法使用
    当然可以。为了提供一个更详细的示例,我将为每个页面(Page1ViewController、Page2ViewController、Page3ViewController和Page4ViewController)编写示例代码,以展示如何通过代理模式将数据从Page4传递回Page1。定义Page4的代理协议首先,定义一个在Page4ViewController中使用的......
  • IOS申请证书步骤
    保姆级苹果个人开发者账号、企业开发者账号ios证书申请流程和签名步骤 苹果开发者网站的申请就不做介绍了,进入苹果开发者网站会员中心一、钥匙串申请MAC上打开钥匙串 点击后,输入相应的信息;然后点击保存到磁盘; 文件扩展名为cerSigningRequest;最终生成文件如下 二、......
  • 2024最新iOS17.3微信分身详解分享
    微信是目前最流行的社交软件之一,拥有庞大的用户群体。然而,对于一些需要同时使用多个微信账号的用户来说,使用官方版微信就显得有些不方便。iOS分身微信软件可以解决这个问题,它可以让用户在同一台设备上同时登录多个微信账号,从而实现工作生活两不误。iOS分身微信软件的优势iOS分身微......