天天看点

iosGCD多线程之创建多线程

喔尽量分成一小节一小节的写。这样也难让大家看的清楚些。我这里有三种创建线程的方法。代码如下

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

}

//当用户点击屏幕,执行线程

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

{

       [self testThread];

}

-(void)testThread

{

    //取到当前线程,在这里就是主线程

    NSThread *curThread = [NSThread currentThread];

    NSLog(@"curThread = %@",curThread);

//    //取到主线程的方法

//    NSThread *mainThread = [NSThread mainThread];

//    NSLog(@"mainThread = %@",mainThread);

//    

    [self createThread1];

}

-(void)createThread1

{

    //一个NSThread对象就是一个线程

    // 参数1,2 : 指定线程中由参数1调用参数2的方法

    // 参数3 : 给参数2指定的方法传递实参

    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(threadMain:) object:@"线程创建方式1"];

    [thread setName:@"我叫二蛋"];

    [thread start];

}

-(void)createThread2

{

    [NSThread detachNewThreadSelector:@selector(threadMain:) toTarget:self withObject:@"线程创建方式2"];

}

-(void)createThread3

{

    [self performSelectorInBackground:@selector(threadMain:) withObject:@"线程创建方式3"];

}

-(void)threadMain:(id)obj

{

    for (int i = 0; i<1000; i++) {

        NSLog(@"i = %d,obj = %@,thread = %@",i,obj,[NSThread  currentThread]);

    }

}

iosGCD多线程之创建多线程

当然大家还是需要多用,就像吃饭,吃的多了还能挑刺,继续下一篇,今天晚上3更。哈哈