IOS开发网络第一天之02NSThread的基本使用

创建子线程的三种方法

1.第一种方式,创建线程后必须要开启线程!

 NSThread *thread = [[NSThread alloc]initWithTarget:

                        self selector:@selector(longTimeOperation) object:nil];

开启线程

    [thread start];

2.这种方式创建就开启

[self performSelectorInBackground:@selector(longTimeOperation)

                           withObject:nil];

3。这种方式创建就开启

[NSThread detachNewThreadSelector:@selector(longTimeOperation)

                             toTarget:self withObject:nil];

#pragma mark - UITouch操作

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

//耗时操作在主线程中执行;

// [self longTimeOperation];

    [self test4];

}

#pragma mark - NSThread//

//NSThread相关方法

- (void) test5{

//1.获取当前线程

    NSThread *thread1 = [NSThread currentThread];

//2.获取主线程

    NSThread *mainThread  = [NSThread mainThread];

    NSLog(@"%@",thread1);

    NSLog(@"%@",mainThread);

}

#pragma mark - NSTread的使用

//NSThread相关的线程属性

- (void)test4{

//1。创建一个线程对象

    NSThread *thread = [[NSThread alloc]initWithTarget:

                        self selector:@selector(longTimeOperation) object:nil];

//2.开启线程

    [thread start];

//===================线程属性=================

//1.线程名

//对于功能的实现没有任何实际意义

//主要是方便调试

    [thread setName:@"下载线程"];

//2.优先级(0-1,值越大,优先级越高)

//优先级不是指哪个优先级高就先被执行,而是线程被调度的次数多(

//cpu调度到得子线程优先级高,执行的时间就越长);

//时间开发中不会去设置优先级;

//如果只有一个子线程,优先级多少都没有任何影响

// [thread setThreadPriority:1];

    //3.

    NSThread *thread2 = [[NSThread alloc]initWithTarget:

                         self selector:@selector(longTimeOperation) object:nil];

    [thread2 start];

    thread2.name = @"解析线程";

}

//隐式创建一个子线程

- (void)test3{

[self performSelectorInBackground:@selector(longTimeOperation)

                           withObject:nil];

}

//快速开启一个子线程

- (void)test2{

//参数1:需要在子线程中执行的方法

//参数2:调用方法的对象

//参数3:方法参数的实参

    [NSThread detachNewThreadSelector:@selector(longTimeOperation)

                             toTarget:self withObject:nil];

}

//创建NSTread对象

- (void) test1{

//1.创建一个NSThread对象

//一个NSThread对象就是一个子线程

//参数1:响应消息的对象;

//参数2:消息(需要在子线程中执行的方法)

//参数3:参数2的方法的参数的实参

    NSThread *thread = [[NSThread alloc]initWithTarget:

                        self selector:@selector(longTimeOperation) object:nil];

//2.开启线程

    [thread start];

}

#pragma mark - 耗时操作

- (void) longTimeOperation{

    for (int i = 0; i<10000; i++) {

NSLog(@"%@",[NSThread currentThread]);

    }

}

评论

暂无评论