这一部分仅作了解,喜欢的同学可以敲一下加深理解。
创建线程提供了三种方式,而线程的状态列举了 启动、睡眠、终端 三种。
//
// ViewController.m
// 34-创建线程的方法(了解)
//
#import "ViewController.h"
@interface ViewController ()
//@property (nonatomic, strong) NSThread *thread; 可以这样声明,但是只能用一次
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)download:(NSString *)url
{
// [NSThread currentThread] 获得当前线程,
// [NSThread mainThread] 获得主线程
NSLog(@"下载东西-----%@-----%@-----%@", url, [NSThread currentThread], [NSThread mainThread]);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 创建线程的方法
// [self createThread1];
// [self createThread2];
// [self createThread3];
// 线程状态
// [self.thread start]; 这是错误的调用方式,因为线程不能重复使用,第一次使用结束之后它就失去了价值,就不能再调用了。
NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(download2) object:nil];
[thread2 start];
}
// 创建线程的方式一(先创建,后启动)
- (void)createThread1
{
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:@"***111***"];
thread.name = @"线程1";
// 启动线程
[thread start];
}
// 创建线程的方式二(创建完成后自动启动)
- (void)createThread2
{
[NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"***222***"];
}
// 创建线程的方式三(隐式创建,自动启动)
- (void)createThread3
{
// 这2个是等价的且都不会创建线程,在当前线程中执行(只是调用了一下download:方法而已)
// [self performSelector:@selector(download:) withObject:@"http://c.gif"];
// [self download:@"http://c.gif"];
[self performSelectorInBackground:@selector(download:) withObject:@"***333***"];
}
- (void)download2
{
NSLog(@"-----begin");
// 睡眠5秒钟(然后再继续下面的)
// [NSThread sleepForTimeInterval:5];
// 3秒后的时间
// NSDate *date = [NSDate dateWithTimeIntervalSinceNow:3];
// [NSThread sleepUntilDate:date];
for (int i = 0; i<100; i++) {
NSLog(@"------%d", i);
// return; 如果这里写上,那么线程就终端了
if (i == 49) {
// 终断线程,输出到49终止
[NSThread exit];
}
}
NSLog(@"-----end");
}
@end