IOS 多線程4種使用方法 :pThread,NSThread,GCD和NSOperation

 pThread  使用方法ide

#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);//線程休眠
    }
}
相關文章
相關標籤/搜索