一个应用程序就相当于一个进程, 在这个进程中包含了很多的线程.
在ios中, 打开一个应用程序, 系统就会给我们创建一个线程, 我们称之为主线程, 其他的就是子线程. 主线程主要管理UI界面, 子线程负责处理数据.
多线程实现的几种方式:
// 1.NSObject的多线程实现方式
- (void)NSObjectThread:(UIButton *)button
{
// 最简单的多线程的执行方式
// 参数1: 需要在后台执行的(子线程)方法
// 参数2: 给这个方法传参
[self performSelectorInBackground:@selector(buttonAction:) withObject:nil];
}
// 2.NSThread实现多线程操作
- (void)NSThreadAction:(UIButton *)button
{
// NSThread 的一个对象 就代表一个线程
// 创建一个NSThread对象 就创建了一个子线程
// 优点: 在所有的多线程的实现方法中,最轻量级
// 优点2: 可以按照要求 任意控制thread对象(控制线程本身)
// 缺点: 控制起来太过繁琐, 不能自己控制线程安全
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(buttonAction:) object:nil];
// 启动线程 执行内部方法
[thread start];
}
// 3.NSOperation实现多线程操作
- (void)NSOperationAction:(UIButton *)button
{
// NSOperation代表一个任务 自己不能实现多线程
// NSOperation是一个抽象类 本身不能直接使用 需要创建一个子类去编写实现的内容
MyOperatio