您的位置:首页 > 产品设计 > UI/UE

UI高级---->多线程总结

2016-08-05 16:48 627 查看
1.NSThread如何启动

四种方式:

//case1

NSThread
*thread1 = [[NSThread
alloc]
initWithTarget:selfselector:@selector(threadCallMethod)
object:nil];//调用start方法启动线程,执行线程里的main方法
[thread1 start]; 

//case2

[NSThread detachNewThreadSelector:@selector(threadCallMethod) toTarget:self
withObject:nil];


//case3

[self performSelectorInBackground:@selector(threadCallMethod)
withObject:nil];


//case4,自定义线程。CustomThread继承NSThread,重写main方法
CustomThread
*ct = [[CustomThread
alloc]
init];

[ct start];

2.线程有哪几种状态?

开始状态,就绪状态,运行状态,阻塞状态,结束状态

3.多线程的优缺点

多线程的优点
(1)能适当提高程序的执行效率;
(2)能适当提高资源利用率(CPU、内存利用率)。
多线程的缺点
(1)开启线程需要占用一定的内存空间(默认情况下,主线程占用1M,子线程占用512KB),如果开启大量的线程,会占用大量的内存空间,降低
程序的性能;
(2)线程越多,CPU在调度线程上的开销就越大;
(3)程序设计更加复杂:比如线程之间的通信、多线程的数据共享。

4.多线程的实现方式

NSThread   

·优点:NSThread 比其他两个轻量级

·缺点:需要自己管理线程的生命周期,线程同步,加锁等 

Cocoa NSOperation (使用NSOperation和NSOperationQueue)

·优点:不需要关心线程管理,数据同步的事情,可以把精力放在自己需要执行的操作上 

GCD  (Grand Central Dispatch)

·GCD是一个替代诸如NSThread, NSOperationQueue, NSInvocationOperation等技术的

一个强大,高效的技术

NSThread的启动方式以上已经实现过了,这里就不重复了

NSOperationQueue 操作队列,用来管理和控制Operation 

//初始化一个操作队列
NSOperationQueue
*queue = [[NSOperationQueue
alloc]
init];
//case1
[queue
addOperationWithBlock:^{
}];
//case2
NSBlockOperation
*bkOperation = [NSBlockOperation
blockOperationWithBlock:^{}];
//case3
NSInvocationOperation
*ivOperation = [[NSInvocationOperation
alloc]initWithTarget:self
se
lector:@selector(threadCallMethod)
object:nil];
[queue
addOperation:ivOperation];
[queue
addOperation:bkOperation];

GCD的实现:

//
创建队列

    //串行

    //label:C语言的字符串 
标示

    //dispatch_queue_attr:队列的类型

    dispatch_queue_t serialQueue =
dispatch_queue_create("---serialQueue----",
DISPATCH_QUEUE_SERIAL);

    //并行

    dispatch_queue_t concurrentQueue =
dispatch_queue_create("---concurrentQueue--",
DISPATCH_QUEUE_CONCURRENT);

 //追加任务到串行队列

    //
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息