多线程之NSThread

我们的App在应用中几乎都需要例如进行下载图片、刷新数据等一些耗时操作,我们一般就用利用到多线程的技术,首先来说说NSThread。一个 NSThread 就代表一个线程对象。NSThread的创建一般有三个方法,下面我来通过代码说明:
1.先创建后启动

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self test1];
}
-(void)test1
{
    NSThread *newThread=[[NSThread alloc] initWithTarget:self selector:@selector(testOperaton:) object:@"Thread"];

    //给新建的线程起一个别名,方便我们在出现Bug的时候可以快速排查
    newThread.name=@"newThread";

    //给新建的线程设置优先级,取值范围是0.0~1.0。默认是0.5(建议最好不要设置)
    newThread.threadPriority=0.5;

    //启动线程; 调用start方法,告诉CPU线程准备就绪;线程被 CPU 调度之后会自动执行@selector()中的方法;
    [newThread start];

}
-(void)testOperaton:(NSString *)object
{
    NSLog(@"longTimeOperaton:%@  %@",[NSThread currentThread],object);
}

输出台的打印信息:
这里写图片描述
2. 创建完自动启动

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self test2];
}
-(void)test2
{
    //这种方式创建无法为线程设置别名
    [NSThread detachNewThreadSelector:@selector(testOperaton:) toTarget:self withObject:@"newThread"];
}
-(void)testOperaton:(NSString *)object
{
    NSLog(@"longTimeOperaton:%@  %@",[NSThread currentThread],object);
}

输出台的打印信息:
这里写图片描述
3. 隐式创建(自动启动)

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self test3];
}
-(void)test3
{
    [self performSelectorInBackground:@selector(testOperaton:) withObject:@"newThread"];
}
-(void)testOperaton:(NSString *)object
{
    NSLog(@"longTimeOperaton:%@  %@",[NSThread currentThread],object);
}

再来说下NSThread中常会用到的方法:
名字/获得主线程/获得当前线程/阻塞线程/退出线程
// 不常用: 栈区大小/优先级
1> 获得当前线程
+ (NSThread *)currentThread;

2> 获得主线程
+ (NSThread *)mainThread;

3> 睡眠(暂停)线程
+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;

4> 设置线程的名字
- (void)setName:(NSString *)n;
- (NSString *)name;
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值