分享五

今天又和大家分享的知识点吧


进程和线程的概念
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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值