多线程iOS多线程

iOS perfromSelector 和线程的关系

2022-04-12  本文已影响0人  Edviin_2de8

perfromSelector:withObject: afterDelay:

image.png

问题

为什么不打印3

测试1
- (void)test2{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"1");
        [[NSRunLoop currentRunLoop] run];
        [self performSelector:@selector(test) withObject:nil afterDelay:1];
        NSLog(@"3");
        NSLog(@"%@",[NSRunLoop currentRunLoop]);
    });
}
- (void)test{
    NSLog(@"2");
    
}

结果只会只会打印1 ,3 不会打印2

- (void)test2{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"1");
        
        [self performSelector:@selector(test) withObject:nil afterDelay:5];
        [[NSRunLoop currentRunLoop] run];
        NSLog(@"3");
        NSLog(@"%@",[NSRunLoop currentRunLoop]);
    });
}
- (void)test{
    NSLog(@"2");
    
}

结果打印123

- (void)test2{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"1");
        
        [self performSelector:@selector(test) withObject:nil afterDelay:5];
        NSLog(@"4");
        [[NSRunLoop currentRunLoop] run];
        NSLog(@"3");
//        NSLog(@"%@",[NSRunLoop currentRunLoop]);
    });
}
- (void)test{
    NSLog(@"2");
    
}

会打印1-4-2-4

总结

performSelectorOnMainThread

- (void)test3{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"1");
        
        [self performSelectorOnMainThread:@selector(test) withObject:nil waitUntilDone:YES];
        NSLog(@"3");
    });
}
- (void)test{
    NSLog(@"%@",[NSThread currentThread]);
    sleep(3);
    NSLog(@"2");
    
}

答案是 1,隔3秒然后打印2,在打印3

performSelectorInBackground

- (void)test4{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"1");
        
        [self performSelectorInBackground:@selector(test) withObject:nil];
        NSLog(@"3");
    });
}
- (void)test{
    NSLog(@"%@",[NSThread currentThread]);
    sleep(3);
    NSLog(@"2");
    
}

打印结果为132,

performSelector:withObject

- (void)test5{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"1");
        
        [self performSelector:@selector(test) withObject:nil];
        NSLog(@"3");
    });
}
- (void)test{
    NSLog(@"%@",[NSThread currentThread]);
    sleep(3);
    NSLog(@"2");
    
}

打印结果为123,
说明 performSelector:withObject 会阻塞当前线程,等方法执行完之后,才可以向下执行,
performSelector方法里面是同步的,如果有异步方法,也不会阻塞当前线程

上一篇 下一篇

猜你喜欢

热点阅读