多线程 NSThread(子线程)的使用

创建一个继承自"NSThread"的类并命名为"SubThread"(可以随意命名)

#import "SubThread.h"

@implementation SubThread

//复写main函数 作为入口函数
-(void)main
{
    NSLog(@"subThread");
}


@end

           回到 "ViewController.m" 文件 调用刚才创建的 "SubThread.h" 文件
#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];
    
    
}

-(void)backMainThread:(UIImage *)img
{
    //获取到图片对象 在主线程中设置UIImageView的image属性
    
}
@end

你可能感兴趣的:(多线程 NSThread(子线程)的使用)