#import "HMViewController.h" @interface HMViewController () @end @implementation HMViewController - (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
} //下载操作,
- (void)download:(NSString *)url
{
NSLog(@"下载东西---%@---%@", url, [NSThread currentThread]); } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self createThread3];
} /**
* 创建线程的方式3
隐式创建线程并自动启动线程
*/
- (void)createThread3
{
// 这2个不会创建线程,在当前线程中执行
// [self performSelector:@selector(download:) withObject:@"http://c.gif"];
// [self download:@"http://c.gif"]; //这个隐式创建线程,在后台会自动创建一条子线程并执行download方法,
[self performSelectorInBackground:@selector(download:) withObject:@"http://c.gif"];
} /**
* 创建线程的方式2
创建线程后自动启动线程
*/
- (void)createThread2
{
//从当前线程中分离出一条新的线程
[NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"http://a.jpg"];
} /**
* 创建线程的方式1
创建线程后不会自动启动,需要写一句启动才会启动线程
这种创建线程的方法是3种当中最好的,可以对线程进行详细的设置 */
- (void)createThread1
{
// 创建线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:@"http://b.png"]; //线程的名字,打印线程的时候可以看到打印的线程的名字
thread.name = @"下载线程"; object://你开辟线程要执行的方法要传的参数,比如这里传一个url,传到download方法里
//这个参数是要从当前线程传到子线程中去的 // 启动线程(调用self的download方法) 只有启动线程才会调用self的download方法
[thread start]; //必须有这一句才能启动线程
//并且执行过程是在子线程中执行的,就是新开辟的一条线程 把耗时操作成功放到子线程中去 [NSThread mainThread];//获得主线程
NSThread *current=[NSThread currentThread];//获得当前线程 [thread isMainThread];//判断当前线程(新创建线程)是否为主线程,返回Bool值
[NSThread isMainThread];// 判断当前执行代码的方法是否在主线程,返回Bool值 } @end