//0、多线程:
//Pthread
//NSThread
//NSOperationQueue
//GCD
//1、进程和线程:
//进程 :app无法独立运行,需要分配内存空间。每个app至少有一个进程,是应用程序的开始(缺点:不能同时执行)。
//线程 :可以多个线程同时并发执行,防止主线程阻塞,增加运行效率,是应用程序运行的最小单元。
//主线程:又叫UI主线程,程序运行都是在主线程加载,记载视图,但是不可以加载数据,因为请求网络数据的时间比较长,出现空白现象。
//子线程:灭法加载UI,UI只能在主线程中加载。
//
//2、NSThread
//轻量级的方式:自己管理线程的生命周期,线程同步;线程同步对数据的加锁会有一定的系统开销。
@interface ViewController ()
@property (nonatomic, weak) UILabel * label;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor redColor];
// //1、实例方法开启多线程(必须调用start方法)(以下两个线程都调用show方法,但是调用的前后顺序不确定)
// NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(show:) object:@"11111"];
// thread.name = @"线程2";
// thread.threadPriority = .1;//只能让线程较早执行,但是因为代码的执行速度不同,所以不能决定谁先执行(默认值:0.5)
// [thread start];
//
//
// NSThread * thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(show:) object:@"22222"];
// [thread2 start];
//
//
// //2、类方法开启多线程(不需要start)
// [NSThread detachNewThreadSelector:@selector(show:) toTarget:self withObject:@"33333"];
//
//
// //3、线程阻塞
// [NSThread sleepForTimeInterval:3];//写在这里,会阻塞主线程显示手机界面,但是不会阻塞上边的子线程执行show方法
[NSThread sleepUntilDate:nil];//不常用
[self _openThread];
//
// NSLog(@"44444");
//
// //4、隐式开启多线程(轻量级)
// [self performSelectorInBackground:@selector(show:) withObject:@"55555"];
//
//5、(更新ui只能在主线程中进行。否则有的时候不会显示)三秒钟之后更改label内容
UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 100, 20)];
label.backgroundColor = [UIColor greenColor];
label.center = self.view.center;
self.label = label;
[self.view addSubview:label];
[self performSelectorInBackground:@selector(show2:) withObject:@"222"];
}
- (void)_openThread
{
//判断是不是主线程
NSLog(@"%i", [NSThread isMainThread]);
//是不是多线程
// NSLog(@"%i", [NSThread isMultiThreaded]);
NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(show:) object:@"66666"];
[NSThread sleepForTimeInterval:3];
[thread start];
[NSThread sleepForTimeInterval:3];
}
- (void)show:(NSString *)info
{
NSThread * thread = [NSThread currentThread];
NSLog(@"%@", thread);
}
- (void)show2:(NSString *)info
{
[NSThread sleepForTimeInterval:3];
[self performSelectorOnMainThread:@selector(updateUI:) withObject:@"hello" waitUntilDone:NO];
}
- (void)updateUI:(NSString *)info
{
NSLog(@"%i", [NSThread isMainThread]);
self.label.text = info;
self.label.backgroundColor = [UIColor whiteColor];
}