多线程 - 1

来源:互联网 发布:网络蜘蛛 重访策略 编辑:程序博客网 时间:2024/05/17 01:19

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;// equivalent to the first method with kCFRunLoopCommonModes

GCD普及的现在,相信这个方法大家都相当陌生,如果让你回答最后一个阻塞参数,很多人都回答不出来


在这里简单讲讲,这个wait参数是判断是否阻塞当前线程(方法),给出下面的例子就能明白了


当设置成YES的时候,会先执行指定方法执行,然后再完成当前线程操作,例如:

- (void)viewDidLoad{    [super viewDidLoad];        [self performSelectorOnMainThread:@selector(mainThreadFunc:) withObject:@"first Param" waitUntilDone:YES];        NSLog(@"here several next 1");        NSLog(@"here several next 2");    NSLog(@"here several next 3");}- (void)mainThreadFunc:(id)sender{    NSLog(@"main thread func test this .");}


我们可以加入一些耗时操作,例如大数组的生成和排序如下来验证:

- (void)viewDidLoad{    [super viewDidLoad];        [self performSelectorOnMainThread:@selector(mainThreadFunc:) withObject:@"first Param" waitUntilDone:NO];        NSLog(@"here several next 1");        NSLog(@"here several next 2");    NSLog(@"here several next 3");- (void)mainThreadFunc:(id)sender{    NSLog(@"main thread func test this .");    NSMutableArray * arr = [NSMutableArray array];        for (unsigned int i = 0; i < 100000; i++)    {        [arr addObject:[NSString stringWithFormat:@"obj%d", i]];    }        NSLog(@"arr[99999] is : %@", arr[99999]);        int i = 0;    int * sortArr;        sortArr = (int *)calloc(1000, sizeof(int));        for (i = 999; i > 0; i--)    {        sortArr[i] = i;    }        for (i = 0; i < 10; i++)    {        for (int j = 1; j < 10 - i; j++)        {            if (sortArr[j-1] > sortArr[j])            {                int temp = sortArr[j-1];                sortArr[j-1] = sortArr[j];                sortArr[j] = temp;            }        }    }        for (i = 0; i < 1000; i++)    {        NSLog(@"sorted arr is : %d", sortArr[i]);    }        free(sortArr);}


可以看到效果一样。同样的道理,如果设置成NO效果即反过来


但是要小心延迟操作,如果在下面添加延迟操作,那结果就不一定了,例如在指定方法安排一个延迟的操作,是不能阻塞以等待这个延迟操作的








0 0
原创粉丝点击