多线程的用法 FWD

 

// ============== 第一种 ==============
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(mutableThread:) object:nil];
[t start];
 
// ============== 第二种 ==============
NSThread detachNewThreadSelector:@selectorc(mutableThread) toTarget:self withObject:nil];
 
// ============== 第三种 ==============
[self perforamSelectorInBackground:@selector(mutableThread) 
 
// ============== 第四种 ==============
NSOperationQueue *threadQueue = [[NSOperationQueue alloc] init];
[threadQueue addOperationWithBlock:^(void) {
    Thread *t = [NSThread currentThread];
    if (![t isMainThread]) {
        NSLog(@”是多线程”);
    }
}];
 
// ============== 第五种 ==============
// 创建线程队列(线程池)
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
// 设置并发数
[operationQueue.maxConcurrentOperationCount = 1;
// 创建一个线程
NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(thread1) object:nil];
// 设置线程优先级
[operation1 setQueuePriority:NSOperationQueuePriorityVeryLow];
// 创建一个线程
NSInvocationOperation *operation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(thread2) object:nil];
// 设置线程优先级
[operation2 setQueuePriority:NSOperationQueuePriorityHigh];
// 将线程添加到线程池中
[operationQueue addOperation:operation1];
[operationQueue addOperation:operation2];
 
// 子线程执行的方法
– (void)mutaleThread {
    // 创建一个自动释放池,释放子线程使用的资源
    @autoreleasePool {
        for (int i = 0; i < 50; i++) {
            NSLog(@”子线程”);
        }
        BOOL isMulti = [NSThread isMultiThread];
        if (!isMulti) {
            // 参数waitUntilDone:是否等待refreshUI执行结束
            [self performSelectorOnMainThread:@selector(refreshUI) withObject:nil waitUntilDone:YES];
        }
        NSLog(“finish”);
    }
}
 
– (void)refreshUI {
    BOOL isMulti = [NSThread isMultiThread];
    if (isMulti) {
        NSLog(@”刷新UI”);
    }
}
 
 
NSThread类的常用方法
// 判断当前线程是否是多线程
 
+ (BOOL)isMultiThreaded;
// 判断当前线程对象
 
+ (NSThread *)currentThread;
// 使当前线程休眠指定的时间,单位为秒
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
 
// 退出当前线程
+ (void)exit;
 
// 判断当前线程是否是主线程
+ (BOOL)isMainThread;
 
// 启动该线程
– (void)start;
 
// ============== 第六种 ==============
// 创建一个队列
dispatch_queue_t queue = dispatch_queue_create(“test”, NULL);
// 创建异步线程
dispatch_async(qeuue, ^{
    for (int i = 0; i < 50; i++) {
        NSLog(@”多线程”);
    }
    // 回到主线程执行,主线程调用此block
    dispatch_sysnc(dispatch_get_main_queue(), ^{
        if ([NSThread isMainThread]) {
            NSLog(“是主线程”);
        }
    });
});

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s