objective-c开发——多线程(NSThread)

时间:2022-09-07 20:04:31

多线程是什么?

首先,什么是线程,你可以理解为,线程是进程的进程。

进程是神马?

进程是计算机里的一个一个小任务。

我这么跟你说吧。

我们的主程序是一根筋的笨蛋,一个时间内只能干一件事儿。并且,所有操作UI控件的程序,只能由主线程来完成。

但是,例如,访问网络这种耗时、费力,还可能卡死的事情,如果放在主程序中,那用户体验可是太不好了,

因为,这事儿没完,后面的事情就干不了。

主程序就是这样,一件事情干完了,再干另一件事情。这事儿没干完,就等着。

那用户就在这儿等着?你有个进度条还好,要是连进度条都没有,我靠,用户以为死机了呢。

我们当然就有解决办法——多线程。

多线程不仅仅是OC的技术,JAVA,.NET都有相关的解决方案,只是语法框架不一样而已。

今天主角是OC,我们就来看看OC中是怎么处理多线程的。

objective-c开发——多线程(NSThread)

这当然不是我总结的,拿来用一下。

第一个我们就不说了,几乎不用的东西,我也不会,咱们从NSThread说起。

下面是一个Demo,就一个ViewController,点击屏幕空白处运行

 

//

//  ViewController.m

//  NSThreadTest

//

//  Created by tarena on 16/3/28.

//  Copyright © 2016 tarena. All rights reserved.

//

 

#import "ViewController.h"

 

@interface ViewController ()

 

@end

 

@implementation ViewController

 

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

 

    //方式一:

    //object 为子线程方法的参数

    NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(method:) object:@"方式一启动"];

    //需要启动一下

    [thread1 start];

    

    //方式二:

    //自动启动

    [NSThread detachNewThreadSelector:@selector(method:) toTarget:self withObject:@"方式二启动"];

    

    //方式三:

    [self performSelectorInBackground:@selector(method:) withObject:@"方式三启动"];

    

 

 

 

}

 

-(void)method:(NSString*)name{

 

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

        NSLog(@"我是%@,i=%d",name,i);

    }

}

 

- (void)viewDidLoad {

    [super viewDidLoad];

    

}

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end

以下是控制台部分截图,看,子线程们穿插着运行着,主线程一点也不卡。

objective-c开发——多线程(NSThread)