#import "ViewController.h"
/**
* 一个NSThread对象就代表一条线程
创建 启动线程
// 创建
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
// 启动
[thread start];
*/
// 调用优先级
//threadPriority
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)download:(NSString *)url {
for (int i = 1; i <=100; i++) {
if (i == 49) {
[NSThread exit];
}
}
// 拿到主线程
NSLog(@"%@",[NSThread mainThread]);
NSLog(@"%@",url);
NSLog(@"%@",[NSThread currentThread]);
// 两种睡法
// 睡眠五秒钟
[NSThread sleepForTimeInterval:3];
// 3秒后的时间
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:3];
[NSThread sleepUntilDate:date];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self createThread2];
}
// 创建线程方式3
- (void)createThread3 {
// [self performSelector:@selector(download:) withObject:@"http://url.jpg"];
// [self download:@"http://url.jpg"];
[self performSelectorInBackground:@selector(download:) withObject:@"http://url.jpg"];
}
/**
* 线程3线程2 无法对线程进行详细设置
*/
// 创建线程方式2
- (void)createThread2 {
// 从当前线程分离出一条新的线程
[NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"http://a.jpg"];
}
// 创建线程方式1
- (void)creatThread1 {
// 创建线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:nil];
// 线程一开启就会放入‘可调度线程池’
// sleep - > blocked 阻塞状态
// 如果线程睡着了,达不到运行的状态,没有运行的能力,
// 就会从可调度线程池中移除,但是不会被销毁
// dead
// 如果线程任务执行完毕,异常强制退出 就是 dead
// 线程的名字
thread.name = @"下载线程";
[thread isMainThread];
// 启动线程 调用download方法
[thread start];
// 判断当前方法是否在主线程中
[NSThread isMainThread];
}
// 线 程 的 状 态
// 新建 - 就绪 - 开始执行 - 睡眠 - 死亡
/**
* 控制线程状态
启动线程
start - 就绪状态-》运行状态 当线程任务执行完毕,自动进入死亡状态
阻塞线程、暂停线程
+ (void)sleepUntilData:(NSData*)data;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
// 进入阻塞状态
强制停止线程
+ (void)exit;
// 进入死亡状态
一旦进入死亡状态,不能再次开启任务
*/
NSThread
最新推荐文章于 2024-09-29 21:07:28 发布