iOS NSThread基本使用

#import"ViewController.h"

#import"XMGThread.h"

@interfaceViewController()

@end

@implementationViewController

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event

{

[selfcreateNewThread1];

}

//1.alloc init创建线程,需要手动启动线程

//线程的生命周期:当任务执行完毕之后被释放掉

-(void)createNewThread1

{

//1.创建线程

/*

第一个参数:目标对象self

第二个参数:方法选择器调用的方法

第三个参数:前面调用方法需要传递的参数nil

*/

XMGThread*threadA = [[XMGThreadalloc]initWithTarget:selfselector:@selector(run:)object:@"ABC"];

//设置属性

threadA.name=@"线程A";

//设置优先级取值范围0.0 ~ 1.0之间最高是1.0默认优先级是0.5

threadA.threadPriority=1.0;

//2.启动线程

[threadAstart];

//NSThread *threadB = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"ABC"];

//threadB.name = @"线程b";

//threadB.threadPriority = 0.1;

//[threadB start];

//

//NSThread *threadC = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"ABC"];

//threadC.name = @"线程C";

//[threadC start];

}

//2.分离子线程,自动启动线程,

-(void)createNewThread2

{

[NSThreaddetachNewThreadSelector:@selector(run:)toTarget:selfwithObject:@"分离子线程"];

}

//3.开启一条后台线程

-(void)createNewThread3

{

[selfperformSelectorInBackground:@selector(run:)withObject:@"开启后台线程"];

}

-(void)run:(NSString*)param

{

//NSLog(@"---run----%@---%@",[NSThread currentThread].name,param);

for(NSIntegeri =0; i<10000; i++) {

NSLog(@"%zd----%@",i,[NSThreadcurrentThread].name);

}


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 原文地址 http://www.cnblogs.com/kenshincui/p/3983982.html 大家都...
    怎样m阅读 1,303评论 0 1
  • 进程和线程 首先,在了解多线程之前要了解什么是进程,什么是线程 什么是进程呢?进程是指在系统中正在运行的一个应用程...
    搁浅的青蛙阅读 408评论 0 0
  • 在这篇文章中,我将为你整理一下 iOS 开发中几种多线程方案,以及其使用方法和注意事项。当然也会给出几种多线程的案...
    伯恩的遗产阅读 274,900评论 251 2,331
  • 第一次读以动物的眼光看待这个世界,黑骏马从四岁起开始被主人正规训练,沉稳睿智的妈妈经常教导它不要学外边的马儿那样狂...
    正念如是阅读 939评论 0 0
  • 1. 相关书箱:《微习惯》 2. 每天制定小目标,不要太大,否则增加 阻力。 微习惯呀。 嗯,把目标定低一点,不会...
    小宁静致远阅读 217评论 0 2