网络开始---多线程---NSThread-01-基本使用(了解)(二)

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

1#import"HMViewController.h"23@interfaceHMViewController ()45@end67@implementationHMViewController89- (void)viewDidLoad10{11[super viewDidLoad];12//Do any additional setup after loading the view, typically from a nib.13}1415//下载操作,16- (void)download:(NSString *)url17{18NSLog(@"下载东西---%@---%@", url, [NSThread currentThread]);192021222324}2526- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event27{28[self createThread3];29}3031/**32* 创建线程的方式333隐式创建线程并自动启动线程34*/35- (void)createThread336{37//这2个不会创建线程,在当前线程中执行38//[self performSelector:@selector(download:) withObject:@"http://c.gif"];39//[self download:@"http://c.gif"];4041//这个隐式创建线程,在后台会自动创建一条子线程并执行download方法,42[self performSelectorInBackground:@selector(download:) withObject:@"http://c.gif"];43}4445/**46* 创建线程的方式247创建线程后自动启动线程48*/49- (void)createThread250{51//从当前线程中分离出一条新的线程52[NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"http://a.jpg"];53}5455/**56* 创建线程的方式157创建线程后不会自动启动,需要写一句启动才会启动线程58这种创建线程的方法是3种当中最好的,可以对线程进行详细的设置5960*/61- (void)createThread162{63//创建线程64NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(download:)object:@"http://b.png"];6566//线程的名字,打印线程的时候可以看到打印的线程的名字67thread.name =@"下载线程";6869object://你开辟线程要执行的方法要传的参数,比如这里传一个url,传到download方法里70//这个参数是要从当前线程传到子线程中去的7172//启动线程(调用self的download方法) 只有启动线程才会调用self的download方法73[thread start];//必须有这一句才能启动线程74//并且执行过程是在子线程中执行的,就是新开辟的一条线程 把耗时操作成功放到子线程中去7576[NSThread mainThread];//获得主线程77NSThread *current=[NSThread currentThread];//获得当前线程787980[thread isMainThread];//判断当前线程(新创建线程)是否为主线程,返回Bool值81[NSThread isMainThread];//判断当前执行代码的方法是否在主线程,返回Bool值8283}8485@end

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航