- (void)viewDidLoad {
[super viewDidLoad];
//1.创建NSThread对象
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(downloadImage:) object:@"Hello"];
//设置子线程的名字
thread.name = @"这是我的子线程";
//3.启动子线程的任务Task
[thread start];
NSLog(@"-----由主线程执行如下代码:%@", [NSThread currentThread]);
}
//2.将耗时操作指定给子线程方法(对象)
- (void)downloadImage:(NSString *)string {
//由子线程执行
NSLog(@"由子线程执行如下代码:%@", [NSThread currentThread]);
//让子线程休眠5s
[NSThread sleepForTimeInterval:5];
for (int i = 0; i < 5; i++) {
NSLog(@"执行次数:%d", i);
if (i == 1) {
NSLog(@"%@",string);
//线程退出
[NSThread exit];
}
}
}
网友评论