您的位置:首页 > 移动开发 > IOS开发

NSThread - 1

2015-10-28 12:12 281 查看
了解多线程之前先要明白基本的操作系统的调配的概念: 线程 进程 自行百度去 ~

本文章学习于文顶顶大神,例子也是出自他之手,如有侵权告知必删。

多线程相关内容
http://www.cnblogs.com/wendingding/tag/%E5%A4%9A%E7%BA%BF%E7%A8%8B%E7%AF%87/
#import "MultiThreadViewController.h"

@implementation MultiThreadViewController

- (void)viewDidLoad
{
[super viewDidLoad];

[self.view setBackgroundColor:[UIColor lightGrayColor]];

UITextView* textView = [[UITextView alloc] init];
[textView setFrame:CGRectMake(0, 0, 200, 100)];
[textView setCenter:CGPointMake(self.view.center.x, self.view.center.y)];
[textView setBackgroundColor:[UIColor whiteColor]];
[self.view addSubview:textView];

UIButton* headbtn = [UIButton buttonWithType:UIButtonTypeCustom];
headbtn.frame = CGRectMake(0, 0, 50, 50);
[headbtn setCenter:CGPointMake(self.view.center.x, self.view.center.y + 150)];
[headbtn setBackgroundColor:[UIColor blueColor]];
[headbtn setTitle:@"点我!" forState:UIControlStateNormal];
[headbtn setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
[headbtn addTarget:self action:@selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:headbtn];

}

- (void)buttonClicked:(id)sender
{
NSThread* current = [NSThread currentThread];

for (int i = 0; i< 10000; i++)
{
NSLog(@"btnClick---%d---%@",i,current);
}

}

@end


很显然的线程阻塞,点击按钮之后会发现短时间内点击textView 是没有任何反应的。

希望学习完多线程之后会知道怎么用多种方法解决。

首先入手的就是NSThread 最传统的线程类。别的属性和方法都望文能生义,但是有几个需要特别指出。

酷狗的面试就有这个方法的参数意义的题目:

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;


前两个参数都很好理解,最后一个布尔的wait参数该如何理解?



如果当前线程是就主线称,则马上执行该方法。

如果当前的线程不是主线程:

当YES,则会阻塞线程,必须等待当前线程执行完毕,才能执行该方法。

当NO , 则不阻塞线程,直接在主线程执行该方法。

马上执行的线程方法:

+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullable id)argument;


用NSThread多种创建线程的方法:

1.最简单的初始化方法:

- (void)buttonClicked:(id)sender
{
//输出当前的线程是什么

NSThread* current = [NSThread currentThread];

NSLog(@"btnClick --- %@", current);

//获取主线程

NSThread* main = [NSThread mainThread];

NSLog(@"main  --- %@", main);

//耗时操作
[self creatNSThread];
}

- (void)creatNSThread
{
NSThread* thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"线程A"];

thread1.name = @"线程A";

//开启线程
[thread1 start];

NSThread* thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"线程B"];

thread2.name = @"线程B";

[thread2 start];
}


输出结果如下:



注意到,默认的环境在主线程,而后来创建的线程是非主线程上,并且每初始化一次创建一个新的线程,另外仔细观察上面有一次输出是BB,说明并不是严格顺序的串行执行,这里需要以后的进一步理解。

在上面程序上打的断点如下:



thread类的结构也是非常简单,一个指向NSThread Class 的isa 指针。另外一个私有的成员变量,还有一个目前还不是很知悉其意的字节成员变量。

下篇继续...

参考: 

Reference - 1  : 系列文章 :http://blog.csdn.net/totogo2010/article/details/8010231

Reference - 2  : MJ  大神  :  http://blog.csdn.net/q199109106q/article/details/8565844 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iOS 多线程 NSThread