ViewController.m
#import "ViewController.h"
#import "SubThread.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//注意:显示创建需要自己管理线程 列如:开启和关闭
//注意:线程间通信,任何对UI进行的操作一定要回到主线程
//NSThread四种创建方式.///////
[self createThread];
//thread配置属性
// [self configuration];
}
-(void)createThread
{
//NSThread四种创建方式.///////
//第一种显示创建
NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(threadAction) object:nil];
//开启子线程
[thread1 start];
//第二种 隐式创建
// [NSThread detachNewThreadSelector:@selector(threadAction) toTarget:self withObject:nil];
//第三种 隐式创建
// [self performSelectorInBackground:@selector(threadAction) withObject:nil];
//第四种 显示创建
// SubThread *subthread = [[SubThread alloc] init];
//
// [subthread start];
}
//thread配置属性
-(void)configuration
{
NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(subThreadAct) object:nil];
//设置线程名字
thread2.name = @"subThread";
//设置栈空间 以kb作为单位
thread2.stackSize = 100;
//设线程的字典属性
[thread2.threadDictionary setObject:@"AFN" forKey:@"identifier"];
//设置线程优先级 范围:0.0 - 1.0 默认的线程优先级为0.5
thread2.threadPriority = 1;
//设置线程优先级 优先级为枚举值 线程启动前可以设置该属性,启动后将无法设置
thread2.qualityOfService = NSQualityOfServiceUserInteractive;
//启动线程 一般放在最后
[thread2 start];
//查看某线程的状态
NSLog(@"executing:%d",thread2.executing);
NSLog(@"finished:%d",thread2.finished);
NSLog(@"cancelled:%d",thread2.cancelled);
}
//线程实现的方法
-(void)threadAction
{
NSLog(@"子线程");
NSLog(@"isMainThread %d",[NSThread isMainThread]);
NSLog(@"isMultiThread %d",[NSThread isMultiThreaded]);
NSLog(@"MainThread %@",[NSThread mainThread]);
NSLog(@"currentThread %@",[NSThread currentThread]);
//退出当前线程
[NSThread exit];
//取消线程的方法
[[NSThread currentThread] cancel];
}
-(void)subThreadAct
{
NSLog(@"%@",[NSThread currentThread]);
UIImage *image = [[UIImage alloc] init];
///////-----线程间通讯的两种方式------////////
//在子线程中回调到主线程执行任务
[self performSelectorOnMainThread:@selector(backMainThread:) withObject:image waitUntilDone:nil];
[self performSelector:@selector(backMainThread:) onThread:[NSThread mainThread] withObject:image waitUntilDone:nil modes:nil];
}
//NSThread 的四种创建方式/线程的实现方法
//NSThread 配置属性