NSTimer

2017-03-01  本文已影响0人  冰室主人
- (void)defaulTimer1{
    NSTimer *_time1=[NSTimer timerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        NSLog(@"%@",[NSRunLoop currentRunLoop].currentMode);
    }];
    [[NSRunLoop currentRunLoop] addTimer:_time1 forMode:NSDefaultRunLoopMode];
}

- (void)defaulTimer2{//scrollview滑动定时器也运行
    NSTimer *_time1=[NSTimer timerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        NSLog(@"%@",[NSRunLoop currentRunLoop].currentMode);
    }];
    [[NSRunLoop currentRunLoop] addTimer:_time1 forMode:NSRunLoopCommonModes];
}


- (void)defaulTimer3{//schedule开头的都默认加到defaultMode中
    NSTimer * _timer=[NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        NSLog(@"%@",[NSRunLoop currentRunLoop].currentMode);
    }];
    [_timer fire];
}

//为了不阻碍主线程,再开一个子线程创建定时器
//创建子线程的RunLoop直接调用[NSRunLoop currentRunLoop];
//一定要让子线程的runLoop跑起来, 不然的话, 子线程一结束, 运行循环立马销毁
- (void)defaulTimer4{
   dispatch_async(dispatch_get_global_queue(0, 0), ^{
       NSTimer *_time1=[NSTimer timerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
           NSLog(@"%@",[NSRunLoop currentRunLoop].currentMode);
       }];
       //NSRunLoop * mainRunLoop=[NSRunLoop mainRunLoop];
       NSRunLoop *currentRunLoop = [NSRunLoop currentRunLoop];
       [currentRunLoop addTimer:_time1 forMode:NSRunLoopCommonModes];
       [currentRunLoop run];
   });
}

//并发调多个接口,都返回更新UI
dispatch_group_enter(_group);
    [_userOtherViewModel getPublish:_userID minID:@"" callback:^(NSInteger state, NSString *msg) {
        dispatch_group_leave(_group);
    }];
    dispatch_group_enter(_group);
    [_userOtherViewModel getMyComment:_userID minID:@"" callback:^(NSInteger state, NSString *msg) {
        dispatch_group_leave(_group);
    }];
    dispatch_group_notify(_group, dispatch_get_main_queue(), ^{
        [ self updateUI];
    });
- (void)semaphore{
    //对有限资源的约束
    dispatch_semaphore_t semaphore=dispatch_semaphore_create(1);
    //value约束几个线程访问资源  getdtablesize()取得程序所有线程的个数
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);//如果有人占用资源,我一直等待
        NSLog(@"我有了资源");
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);//如果有人占用资源,我一直等待
        NSLog(@"我有了资源1");
    });
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        sleep(2);
         NSLog(@"在做事");//比如对文件操作或播视频
        //访问资源的这个人走时发送一个信息量
        dispatch_semaphore_signal(semaphore);
    });
}
上一篇下一篇

猜你喜欢

热点阅读