線程篇-01-NSThread


一.概述

1.使用NSThread創建線程的三種方式和區別.

二.核心

2.1 NSThread創建線程的三種方式和區別.

主要有NSThread對象的創建線程的類方法detachNewThreadSelector:方法, alloc(initWithTarget:selector:object:)方法, performSelectorInBackground:方法.

區別:

1.是前后兩種創建線程的方法, 無法拿到線程, 所以無法給線程設置一些額外信息, 如線程名字等.而且也無法控制線程除創建之外的狀態.而中間這種方法能拿到線程, 給線程設置名字, 還能控制讓線程休眠等.

2.前后兩者不僅僅會創建線程還會自動啟動線程,而中間使用alloc, initWithTarget:selector:object這種則要手動啟動.拿到對應的線程對象, 調用start的方法.

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self createThread3];
    
}

- (void)createThread1 {
    
    // 使用NSThread第一種創建線程的方式
    // 在這個線程上執行當前對象的run方法, 傳遞進來的參數是swp
    [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"swp"];
    
}

- (void)createThread2 {
    // 使用NSThread第一種創建線程的方式
    // 在這個線程上執行當前對象的run方法, 傳遞進來的參數是swp2
    [self performSelectorInBackground:@selector(run:) withObject:@"swp2"];
    
}

- (void)createThread3 {
    
    NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"swp3"];
    // 需要手動啟動線程, 而前面兩種不用手動啟動, 會在創建完后自動啟動線程.
    // 讓CPU立即切換到該線程執行, 其任務就是運行run方法.
    [thread start];
}

- (void)run:(NSString *)param {
    
    for (int i = 0; i < 100; i++) {
        
        NSLog(@"run----%@---%@", [NSThread currentThread], param);
    
    }
    
}


@end


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM