NSThread是OC中的多线程面向对象的一种模式,不需要手动去管理线程我们只负责创建即可,详细用法见如下代码
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self createNewThread1];
}
//1.alloc init 创建线程,需要手动启动线程
//线程的生命周期:当任务执行完毕之后被释放掉
-(void)createNewThread1
{
//1.创建线程
/*
第一个参数:目标对象 self
第二个参数:方法选择器 调用的方法
第三个参数:前面调用方法需要传递的参数 nil
*/
NSThread *threadA = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"ABC"];
//设置属性
threadA.name = @"线程A";
//设置优先级 取值范围 0.0 ~ 1.0 之间 最高是1.0 默认优先级是0.5
threadA.threadPriority = 1.0;
//2.启动线程
[threadA start];
// NSThread *threadB = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"ABC"];
// threadB.name = @"线程b";
// threadB.threadPriority = 0.1;
// [threadB start];
//
// NSThread *threadC = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"ABC"];
// threadC.name = @"线程C";
// [threadC start];
}
//2.分离子线程,自动启动线程
-(void)createNewThread2
{
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"分离子线程"];
}
//3.开启一条后台线程
-(void)createNewThread3
{
[self performSelectorInBackground:@selector(run:) withObject:@"开启后台线程"];
/*
NSObject 的分类,用法与上面相同
@interface NSObject (NSThreadPerformAdditions)
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array;
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
// equivalent to the first method with kCFRunLoopCommonModes
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array NS_AVAILABLE(10_5, 2_0);
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait NS_AVAILABLE(10_5, 2_0);
// equivalent to the first method with kCFRunLoopCommonModes
- (void)performSelectorInBackground:(SEL)aSelector withObject:(nullable id)arg NS_AVAILABLE(10_5, 2_0);
*/
}
-(void)run:(NSString *)param
{
// NSLog(@"---run----%@---%@",[NSThread currentThread].name,param);
for (NSInteger i = 0; i<10000; i++) {
NSLog(@"%zd----%@",i,[NSThread currentThread].name);
}
}
@end
- 阻塞线程,线程会在我们阻塞的时间之后执行
//阻塞线程
//[NSThread sleepForTimeInterval:2.0];
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:3.0]];
网友评论