您的位置:首页 > 其它

分享五

2015-09-02 08:42 381 查看
今天又和大家分享的知识点吧

进程和线程的概念
1、创建线程的几种方法
 //判断返回执行的代码是否在主线程中执行

   
BOOL bool1 = [[NSThread
currentThread]isMainThread];

   
NSLog(@"bool1 is %d",bool1);

    //第一种方式创建线程

    //NSThread *thead=[[NSThread alloc]initWithTarget:self selector:@selector(run) object:nil];

    //手动开启

    //[thead start];

    //第二种方式创建线程
//    [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
//    //第三种方式创建
//    [self performSelectorInBackground:@selector(run) withObject:nil];
//    //第四种方式创建线程

   
NSOperationQueue *queue=[[NSOperationQueue
alloc]init];
//    [queue addOperationWithBlock:^{
//        [self run];
//    }];
//
//    //第五种方式创建

   
NSInvocationOperation *operation = [[NSInvocationOperation
alloc]initWithTarget:self
selector:@selector(run)
object:nil];

    [queue
addOperation:operation];

   

    //第六种方式创建线程
子类化一个person0peration
继承
NSOperation

   

   
for (int
i =
0; i <
100; i ++) {

       
NSLog(@"main is %d",i);

    }

   

   

    }

-(void)run{

   
for (int
i =
0; i <
10; i++) {

       
NSLog(@"thread is %d",i);

    }
}
注意:第三种和第四种是必须要掌握的,其他的可做了解就可以
判断是否在主线程中执行:
//判断返回执行的代码是否在主线程中执行

   
BOOL bool1 = [[NSThread
currentThread]isMainThread];
   
NSLog(@"bool1 is %d",bool1);

GCD

1、串行队列:执行完一个任务才会执行下一个任务,如果有两个串行队列,则两个串行队列可以并发执行
2、并行队列会开很多线程,(测试用了11个任务,结果显示了11个任务同时执行),可以使用信号量来控制线程的数量,函数concurrentQueueTest中,最多同时运行三个任务。

GCD的使用
//创建Serial Dispatch Queue
dispatch_queue_t  serialqueue =
dispatch_queue_create("test",
DISPATCH_QUEUE_SERIAL);
       
 
//创建Concurrent Dispatch Queue
dispatch_queue_t
concurrentqueue =
dispatch_queue_create("concurrent",
DISPATCH_QUEUE_CONCURRENT);
       

       

       
//获取系统的主线程队列

       
dispatch_queue_t queue =
dispatch_get_main_queue();

       

       
//获取系统默认创建的异步线程队列
       
dispatch_queue_t globleQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
0);

注意:一切与UI有关的的操作必须放在主线程中执行,所以要追加到Main Dispath Queue.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: