ios多线程 - NSThread 简介

NSThread 的创建和使用

1) 实例化创建,需要主动开启线程

//创建线程,需要手动启动
/*
*  selector:自定义方法
*  object:给函数传递的参数(例如:下载方法中网址)
*/
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(downLoad:) object:@"url"];
//启动
[thread start];

2) 自动启动的创建方法

//创建线程,自动启动
[NSThread detachNewThreadSelector:@selector(downLoad:) toTarget:self withObject:@"url"];

3) 隐式创建并启动

//其他创建方式(子线程)
[self performSelectorInBackground:@selector(downLoad:) withObject:@"other"];

//其他创建方式(主线程)
[self performSelectorOnMainThread:@selector(downLoad:) withObject:@"main" waitUntilDone:YES];

相关方法:
(1) 获取主线程 [NSThread mainThread];
(2) 获取当前线程 [NSThread currentThread];
(3) 是否为主线程

    @property (readonly) BOOL isMainThread 
    + (BOOL)isMainThread

(4) 线程的名字

@property (nullable, copy) NSString *name

线程状态控制:

(1) 启动线程

- (void)start;

(2) 阻塞(暂停)线程

+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;

(3)强制停止线程

+ (void)exit;

(4) 线程优先级

//线程的调度优先级:调度优先级的取值范围是0.0 ~ 1.0,默认0.5,值越大,优先级越高
+ (double)threadPriority;
+ (BOOL)setThreadPriority:(double)p;

实例:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blueColor];
}

- (void)download:(NSString *)url{
    for (int i =0; i< 5; ++i){
        NSLog(@"%@__%@", url, [NSThread currentThread]);
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"__touchesBegan_%@", [NSThread currentThread]);
    //[self createThread1];
    //[self createThread2];
    [self createThread3];
}

//隐式创建线程,创建完成后自动启动
- (void)createThread3{
    [self performSelectorInBackground:@selector(download:) withObject:@"隐式创建线程,创建完成后自动启动"];
}

//创建线程方法二,创建完成后自动启动
- (void)createThread2{
    [NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"创建完成后自动启动"];
}


//创建线程方法一,需要自己启动
- (void)createThread1{
    //[NSThread currentThread]获取当前线程
    //[NSThread mainThread]获取主线程

    //创建线程A
    NSThread *threadA = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:@"threadA"];
    threadA.name = @"threadA";
    //启动线程
    [threadA start];

    //创建线程B
    NSThread *threadB = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:@"threadB"];
    threadB.name = @"threadB";
    //启动线程
    [threadB start];
}

@end

初始化创建方法,需要手动启动

创建完成后自动启动

隐式创建

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值