为你分析iOS多线程开发
来源:爱站网时间:2018-12-08编辑:网友分享
这篇文章主要介绍了IOS多线程开发之线程的状态 的相关资料,需要的朋友可以参考下
作为一名iOS开发人员,无论你是新手还是大师级别的人,相信对多线程都会陌生,下文是爱站技术频道小编为你分析iOS多线程开发,一起进入下文了解一下吧!
为你分析iOS多线程开发
一、简单介绍
线程的创建:
self.thread=[[NSThread alloc]initWithTarget:self selector:@selector(test) object:nil];
说明:创建线程有多种方式,这里不做过多的介绍。

线程的开启:
[self.thread start];

线程的运行和阻塞:
(1)设置线程阻塞1,阻塞2秒
[NSThread sleepForTimeInterval:2.0];
(2)第二种设置线程阻塞2,以当前时间为基准阻塞4秒
NSDate *date=[NSDate dateWithTimeIntervalSinceNow:4.0];
[NSThread sleepUntilDate:date];

线程处理阻塞状态时在内存中的表现情况:(线程被移出可调度线程池,此时不可调度)

线程的死亡:
当线程的任务结束,发生异常,或者是强制退出这三种情况会导致线程的死亡。

线程死亡后,线程对象从内存中移除。

二、代码示例
代码示例1:
//
// YYViewController.m
// -NSThread-线程的状态
//
// Created by apple on --.
// Copyright (c) 年 itcase. All rights reserved.
//
#import "YYViewController.h"
@interface YYViewController ()
@property(nonatomic,strong)NSThread *thread;
@end
@implementation YYViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//创建线程
self.thread=[[NSThread alloc]initWithTarget:self selector:@selector(test) object:nil];
//设置线程的名称
[self.thread setName:@"线程A"];
}
//当手指按下的时候,开启线程
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//开启线程
[self.thread start];
}
-(void)test
{
//获取线程
NSThread *current=[NSThread currentThread];
NSLog(@"test---打印线程---%@",self.thread.name);
NSLog(@"test---线程开始---%@",current.name);
//设置线程阻塞,阻塞秒
NSLog(@"接下来,线程阻塞秒");
[NSThread sleepForTimeInterval:.];
//第二种设置线程阻塞,以当前时间为基准阻塞秒
NSLog(@"接下来,线程阻塞秒");
NSDate *date=[NSDate dateWithTimeIntervalSinceNow:.];
[NSThread sleepUntilDate:date];
for (int i=; i
打印查看:

代码示例2(退出线程):
//
// YYViewController.m
// -NSThread-线程的状态
//
// Created by apple on --.
// Copyright (c) 年 itcase. All rights reserved.
//
#import "YYViewController.h"
@interface YYViewController ()
@property(nonatomic,strong)NSThread *thread;
@end
@implementation YYViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//创建线程
self.thread=[[NSThread alloc]initWithTarget:self selector:@selector(test) object:nil];
//设置线程的名称
[self.thread setName:@"线程A"];
}
//当手指按下的时候,开启线程
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//开启线程
[self.thread start];
}
-(void)test
{
//获取线程
NSThread *current=[NSThread currentThread];
NSLog(@"test---打印线程---%@",self.thread.name);
NSLog(@"test---线程开始---%@",current.name);
//设置线程阻塞,阻塞秒
NSLog(@"接下来,线程阻塞秒");
[NSThread sleepForTimeInterval:.];
//第二种设置线程阻塞,以当前时间为基准阻塞秒
NSLog(@"接下来,线程阻塞秒");
NSDate *date=[NSDate dateWithTimeIntervalSinceNow:.];
[NSThread sleepUntilDate:date];
for (int i=; i
打印示例:

注意:人死不能复生,线程死了也不能复生(重新开启),如果在线程死亡之后,再次点击屏幕尝试重新开启线程,则程序会挂。

以上内容是爱站技术频道小编给大家介绍的为你分析iOS多线程开发 ,希望大家喜欢。
上一篇:iOS中让键盘消失的方法有哪些
下一篇:iOS中无限循环展示的方法
