多线程 - 03.NSThread使用

来源:互联网 发布:数据工具培训心得 编辑:程序博客网 时间:2024/05/22 00:49

1.NSThread基本使用

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{  // 1.创建子线程    /*     Target: 子线程需要调用谁的方法     selector: 被子线程调用的方法     object: 调用方法时, 给方法传递的参数     */    // 注意: 如果线程正在执行, 那么系统会自动强引用NSThread retained during the execution of the detached thread    // 当线程中的任务执行完毕, 系统会自动释放线程, 对线程进行一次release操作 they are released when the thread finally exits.    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(demo:) object:@"ZJ"];    // 1.1设置线程基本属性    // 设置线程名称    thread.name = @"线程2";    // 设置优先级,注意优先级取值范围时0~1,数值越大,优先级越高,但是优先级越高不代表系统会先执行此线程,而是CPU调度该线程的可能性更大    thread.threadPriority = 0.8;    // 2.启动线程    // 注意点: 如果通过alloc/init创建NSThread, 那么需要手动启动线程    [thread start];}-(void)demo:(NSString *)str{    NSLog(@"%@",str);// 输出结果:ZJ    NSLog(@"%@", [NSThread currentThread]);    // 输出结果:<NSThread: 0x7fab72d11f40>{number = 2, name = 线程2}q    for (int i = 0; i < 100; i++) {        NSLog(@"i = %i",i);    }}

2.NSThread的其他创建方式

    // 方式一:创建子线程    /*     优点:     - 使用简便     - 如果通过detach方法创建线程, 不需要手动调用start启动线程,系统会自动启动     缺点:     - 不可以进行其它设置     - 通过detach方法创建子线程是没有返回值的     应用场景:     - 如果仅仅需要简单的开启一个子线程执行一些操作, 不需要对子线程进行其它设置, 那么推荐使用detach方法创建线程     *///    [NSThread detachNewThreadSelector:@selector(demo:) toTarget:self withObject:@"MrRight"];    // 方式二:    // 系统会自动在后台给我们开启一个子线程, 并且会自动启动该线程执行任务    [self performSelector:@selector(demo:) withObject:@"MrRightZJ"];
0 0
原创粉丝点击