GCD—NSThread-多线程的基本用法

进程概念: 每一个进程中的线程共享内存中内存的资源

多线程概念: 每程序启动时创建主线程(调用main来启动)

/*********线程的创建与启动********/

1.第一种开启新的线程调用mutableThread

NSThread *t = [[NSThread alloc] initWithTarget:self
                                      selector:@selector(mutableThread)
                                        object:nil];
[t start];
// 需要手动开启
2.第二种开启新的线程调用mutableThread
[NSThread datachNewThreadSelector:@selector(mutableThread)
                         toTarget:self withObject:nil];
3.第三种开启新的线程调用mutableThread
[self performSelectorInBackground:@selector(mutableThread)
                       withObject:nil];
4.block语法启动一个线程
NSOperationQueue *threadQueue = [[NSOperationQueue alloc]init];

[threadQueue addOperationWithBlock:^(void){
    NSThread *t = [NSThread currentThread];
}];
5.NSOperation开启一个线程
// 开启队列
NSOperationQueue *threadQueue = [[NSOperationQueue alloc]init];

// 创建线程
NSInvocationOperation *op = [[NSInvocationOperation alloc]initWithTarget:self
                                                                selector:@selector(mutableThread)
                                                                  object:nil];
// 加入队列
[threadQueue addOperation:op];

// 回到主线程调用reloadData方法
[self performSelectorOnMainThread:@selector(reloadData)
                       withObject:nil
                    waitUntilDone:NO];
/********多线程NSThread的常用方法********/
//  判断当前线程是否多线程
+ (BOOL)isMultiThreaded;
//  获取当前线程对象
+ (NSThread *)currentThread;
//  使当前线程睡眠指定的时间,单位为秒
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
//  退出当前线程
+ (void)exit;
//  判断当前线程是否为主线程
+ (BOOL)isMainThread
//  启动该线程
- (void)start
/********GCD*******/
//----------------GCD的详细说明 http://baike.soso.com/v7548422.htm
//GCD(Grand Central Dispatch)是一个大的主题。它可以提高代码的执行效率与多核的利用率
//  创建一个队列
dispatch_queue_t queue = dispatch_queue_create("test", NULL);

//  创建异步线程
dispatch_async(queue, ^{

    //  多线程

    //  回到主线程执行
    dispatch_sync(dispatch_get_main_queue(), ^{

        //  主线程

    });

    dispatch_sync(queue, ^{
        //  在当前线程执行
    });
});
/********自动释放池********/
//  子线程的内存管理
//  创建子线程
[self performSelectorInBackground:@selector(mutableThread)
                       withObject:nil];

- (void)mutableThread {
    //  创建自动释放池
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    //  池中存放各种代码

    //  池中存放各种代码

    [pool release];
}
原文地址:https://www.cnblogs.com/needly/p/3401056.html