IOS 多线程

来源:互联网 发布:全国火灾数据统计 编辑:程序博客网 时间:2024/05/29 17:43

1.线程的创建方式

    //第一种方式    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(runOnWorkThread:) object:@"test"];    //开始运行多线程    [thread start];            //第二种方式    [NSThread detachNewThreadSelector:@selector(runOnWorkThread:) toTarget:self withObject:nil];            //第三种方式    [self performSelectorInBackground:@selector(runOnWorkThread:) withObject:nil];        //主线程执行    [self performSelectorOnMainThread:@selector(runOnMainThread) withObject:nil waitUntilDone:YES];            //第四种方式    NSOperationQueue *operationQueue0 = [[NSOperationQueue alloc] init];    [operationQueue0 addOperationWithBlock:^{        NSLog(@"--Run()--");    }];        //第五种方式    //创建一个线程队列    NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];    //设置线程执行的并发数    operationQueue.maxConcurrentOperationCount = 1;        //创建一个线程操作对象    NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(runOnWorkThread:) object:nil];        //创建一个线程操作对象    NSInvocationOperation *operation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(runOnWorkThread:) object:nil];    //设置线程的优先级    operation2.queuePriority = NSOperationQueuePriorityHigh;        //将线程添加到线程队列中    [operationQueue addOperation:operation1];    [operationQueue addOperation:operation2];        // GCD 第六种方式:创建一个队列    dispatch_queue_t queue = dispatch_queue_create("test", NULL);    dispatch_async(queue, ^{        if ([NSThread isMultiThreaded]) {            NSLog(@"工作线程");        }        // 主线程        dispatch_sync(dispatch_get_main_queue(), ^{            if ([NSThread isMainThread]) {                NSLog(@"主线程");            }        });            });        //通过此种方式,还是同步运行在当前线程上    dispatch_sync(queue, ^{        //当前线程    });    - (void)runOnWorkThread:(NSString *)t {        NSLog(@"工作线程");    }    - (void)runOnMainThread {        if ([NSThread isMainThread]) {            NSLog(@"主线程");    }


 

0 0