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.
//注意:顯示創(chuàng)建需要自己管理線程 列如:開啟和關(guān)閉
//注意:線程間通信,任何對(duì)UI進(jìn)行的操作一定要回到主線程
//NSThread四種創(chuàng)建方式.///////
[self createThread];
//thread配置屬性
// [self configuration];
}
-(void)createThread
{
//NSThread四種創(chuàng)建方式.///////
//第一種顯示創(chuàng)建
NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(threadAction) object:nil];
//開啟子線程
[thread1 start];
//第二種 隱式創(chuàng)建
// [NSThread detachNewThreadSelector:@selector(threadAction) toTarget:self withObject:nil];
//第三種 隱式創(chuàng)建
// [self performSelectorInBackground:@selector(threadAction) withObject:nil];
//第四種 顯示創(chuàng)建
// SubThread *subthread = [[SubThread alloc] init];
//
// [subthread start];
}
//thread配置屬性
-(void)configuration
{
NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(subThreadAct) object:nil];
//設(shè)置線程名字
thread2.name = @"subThread";
//設(shè)置棧空間 以kb作為單位
thread2.stackSize = 100;
//設(shè)線程的字典屬性
[thread2.threadDictionary setObject:@"AFN" forKey:@"identifier"];
//設(shè)置線程優(yōu)先級(jí) 范圍:0.0 - 1.0 默認(rèn)的線程優(yōu)先級(jí)為0.5
thread2.threadPriority = 1;
//設(shè)置線程優(yōu)先級(jí) 優(yōu)先級(jí)為枚舉值 線程啟動(dòng)前可以設(shè)置該屬性,啟動(dòng)后將無法設(shè)置
thread2.qualityOfService = NSQualityOfServiceUserInteractive;
//啟動(dòng)線程 一般放在最后
[thread2 start];
//查看某線程的狀態(tài)
NSLog(@"executing:%d",thread2.executing);
NSLog(@"finished:%d",thread2.finished);
NSLog(@"cancelled:%d",thread2.cancelled);
}
//線程實(shí)現(xiàn)的方法
-(void)threadAction
{
NSLog(@"子線程");
NSLog(@"isMainThread %d",[NSThread isMainThread]);
NSLog(@"isMultiThread %d",[NSThread isMultiThreaded]);
NSLog(@"MainThread %@",[NSThread mainThread]);
NSLog(@"currentThread %@",[NSThread currentThread]);
//退出當(dāng)前線程
[NSThread exit];
//取消線程的方法
[[NSThread currentThread] cancel];
}
-(void)subThreadAct
{
NSLog(@"%@",[NSThread currentThread]);
UIImage *image = [[UIImage alloc] init];
///////-----線程間通訊的兩種方式------////////
//在子線程中回調(diào)到主線程執(zhí)行任務(wù)
[self performSelectorOnMainThread:@selector(backMainThread:) withObject:image waitUntilDone:nil];
[self performSelector:@selector(backMainThread:) onThread:[NSThread mainThread] withObject:image waitUntilDone:nil modes:nil];
}
//NSThread 的四種創(chuàng)建方式/線程的實(shí)現(xiàn)方法
屏幕快照 2016-05-03 下午7.38.39.png
//NSThread 配置屬性
屏幕快照 2016-05-03 下午7.42.51.png