iOS 【Multithreading-创建线程的方式/线程状态(了解)】

这一部分仅作了解,喜欢的同学可以敲一下加深理解。

创建线程提供了三种方式,而线程的状态列举了 启动、睡眠、终端 三种。

//
//  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


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值