IOS 多线程4种使用方法 :pThread,NSThread,GCD和NSOperation

 pThread  使用方法

#import "ViewController.h"
#import <pthread.h>  //pThread需要导入

@interface ViewController ()<UIScrollViewDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *but1 = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 30)];
    [but1 setTitle:@"pThread" forState:UIControlStateNormal];
    [but1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [but1 addTarget:self action:@selector(pThreadClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:but1];
}
#pragma mark pThread是基于C语言的线程  OC里面不常用
- (void)pThreadClick{
    NSLog(@"这是主线程");
    pthread_t pthread;
    //创建一个线程
    pthread_create(&pthread, NULL, run, NULL);  //run 是要执行的方法按照C语言来写
}

void *run(void *dadta){
    NSLog(@"这是子线程");
    for (int i = 0; i< 10; i++) {
        NSLog(@"%d",i);
        sleep(1);//线程休眠
    }
    return NULL;
}

NSThread 的使用

#import "ViewController.h"

@interface ViewController ()<UIScrollViewDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *but1 = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 30)];
    [but1 setTitle:@"NSThread" forState:UIControlStateNormal];
    [but1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [but1 addTarget:self action:@selector(NSThreadClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:but1];
}
#pragma mark NSThread 完全面向对象
- (void)NSThreadClick{
    NSLog(@"这是主线程");
    //第一种方法
    NSThread *thread1 = [[NSThread alloc]initWithBlock:^{
        NSLog(@"这是子线程");
        for (int i = 0; i< 10; i++) {
            NSLog(@"%d",i);
            sleep(1);//线程休眠
        }
    }];
    [thread1 setName:@"thread1"];
    [thread1 setThreadPriority:.7];//设置线程优先级 0-1
    [thread1 start];
   
    NSThread *thread2 = [[NSThread alloc]initWithTarget:self selector:@selector(run) object:nil];
    [thread2 setThreadPriority:.4];//设置线程优先级 0-1
    [thread2 setName:@"thread2"];//设置线程名字
    [thread2 start];
    //第二种方法 通过detachNewThreadSelector 静态方法
//    [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
    //第三种方法  通过Object下的 performSelectorInBackground 方法创建
//    [self performSelectorInBackground:@selector(run) withObject:nil];
}

- (void)run{
    NSLog(@"这是子线程:%@",[NSThread currentThread].name);
    for (int i = 0; i< 10; i++) {
        NSLog(@"%d",i);
        sleep(1);//线程休眠
    }
}

猜你喜欢

转载自my.oschina.net/u/2287505/blog/1632333
今日推荐