OC 线程操作2 NSThread

 

 

方法1 :直接创建 alloc init

- (void)createNSThread111{

/*   

参数1: (nonnull id) 目标对象 self

参数2:(nonnull SEL) 方法选择器 ,调用的方法

参数3:(nullable id) 前面调用方法需要传递的参数 nil *

//1.创建线程 NSThread *thread= [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"abc"];

//2.开启线程 [thread start]; } - (void)run:(NSString *)pama{ NSLog(@"---fun---%@", [NSThread currentThread]); }

打印结果: 2018-06-22 14:10:57.529875+0800 线程操作[6518:200227] ---fun---<NSThread: 0x608000265e40>{number = 3, name = (null)}--abc

 

 

方法2. 分离子线程 ,自动启动线程 detach [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"分离子线程"];

打印结果 : 2018-06-22 14:10:57.530121+0800 线程操作[6518:200228] ---fun---<NSThread: 0x608000265f40>{number = 4, name = (null)}--分离子线程

 

方法3.开启后台一个线程 performSelectorInBackground

[self performSelectorInBackground:@selector(run:) withObject:@"开启一后台线程"];

打印结果 : 2018-06-22 14:10:57.530164+0800 线程操作[6518:200229] ---fun---<NSThread: 0x608000265dc0>{number = 5, name = (null)}

 

--开启一后台线程

第一种 设置线程阻塞,阻塞2秒

+ (void)sleepForTimeInterval:(NSTimeInterval)ti;// 线程停止 几秒

[NSThread sleepForTimeInterval:2.0];

 

第二种设置线程阻塞2,以当前时间为基准阻塞4秒

+ (void)sleepUntilDate:(NSDate *)date;

//控制线程状态

NSDate *date=[NSDate dateWithTimeIntervalSinceNow:4.0];

[NSThread sleepUntilDate:date];

 

// 线程退出

+ (void)exit;   

他人总结 OS开发多线程篇—线程的状态 链接 :https://www.cnblogs.com/wendingding/p/3807184.html

 

原文地址:https://www.cnblogs.com/qingzZ/p/9212734.html