iOS中的线程主要有四种:1.pThread 2.NSThread 3.GCD 4.NSOpreaction

基础知识:
线程、任务和队列的概念:

 

异步、同步 & 并行、串行的特点:

组合特点:

 

 

1.pThread

  C语言所写,面向过程,使用较少.

oc:

#pragma Mark - pThread
- (void)pThreadDemo{
    pthread_t pthread;
    pthread_create(&pthread,NULL,run,NULL);
}

void *run(void *data){
    for (int i = 0; i < 10; i++) {
        NSLog(@"%d",i);
        sleep(1);
    }
    return NULL;
}  

Swift:

    //pThread
    func pThreadDemo() {
        var thread: pthread_t? = nil
        pthread_create(&thread, nil, { (_) -> UnsafeMutableRawPointer? in
            for var i in 0...10{
                print("\(i)")
                sleep(1)
            }
            return nil;
        }, nil)
        
    } 

2.NSThread  

苹果封装后的,面向对象

NSThread有name,threadPriority两个属性,一个设置当前线程的名字,一个设置当前线程的优先级(0-1).

它有3种创建方式.其中第三种performSelector有很多方法:

 在当前线程中执行一个方法:

    [self performSelector:<#(SEL)#>];

在当前线程中执行一个方法并传参:

[self performSelector:<#(SEL)#> withObject:<#(id)#>];

 

在当前程中延迟几秒执行一个方法并传参:

[self performSelector:<#(nonnull SEL)#> withObject:<#(nullable id)#> afterDelay:<#(NSTimeInterval)#> ]

在主线程中执行一个方法并传参:

[self performSelectorOnMainThread:<#(nonnull SEL)#> withObject:<#(nullable id)#> waitUntilDone:<#(BOOL)#>];

在后台(子线程)中执行一个方法并传参:

 [self performSelectorInBackground:<#(nonnull SEL)#> withObject:<#(nullable id)#>];

等等.下面代码会举例说明.

其中,线程锁也很常见,如卖票系统:

    @synchronized(self){
        ...
    }

或者

@property (nonatomic,strong) NSCondition * condition;


   [self.condition lock];
      ...
   [self.condition unlock];

  

OC:

#pragma Mark - NSThreadDemo
- (void)NSThreadDemo{
//    1.通过alloc init 创建
        NSThread * t1 = [[NSThread alloc]initWithTarget:self selector:@selector(nsThreadRun) object:nil];
        [t1 setName: @"我是名字"];    //为线程设置的名字
        [t1 setThreadPriority:0.5];   //设置优先级  0-1
        [t1 start];

//    2.通过detachNewThreadSelector
        [NSThread detachNewThreadSelector:@selector(nsThreadRun) toTarget:self withObject:nil];
        [NSThread detachNewThreadWithBlock:^{
            NSLog(@"%@",[NSThread currentThread].isMainThread == YES ? @"主线程" : @"子线程");
        }];
    
//    3.通过 performSelector
    [self performSelectorInBackground:@selector(nsThreadRun) withObject:nil];
    
}

-(void)nsThreadRun{
NSLog(@"%@",[NSThread currentThread].isMainThread == YES ? @"主线程" : @"子线程");
    for (int i = 0; i < 10; i++) {
        NSLog(@"%d",i);
        sleep(1);
    }
}

 Swift:

    //NSThread
    func nsThreadDemo(){
        //1.通过init创建
        let thread:Thread = Thread.init(target: self, selector: #selector(nsThreadRun), object: nil)
        thread.name = "我是线程"
        thread.threadPriority = 0.4
        thread.start()
        
        //2.detachNewThreadSelector
       Thread.detachNewThreadSelector(#selector(nsThreadRun), toTarget: self, with: nil)
        Thread.detachNewThread {
            print("\(Thread.current.isMainThread)")
        }
        
        //3.performSelector
        self .performSelector(inBackground: #selector(nsThreadRun), with: nil)
        
    }

    @objc func nsThreadRun(){
        print("当前线程是:\(Thread.current.isMainThread ? "主":"子")")
        for var i in 0...10{
            print("\(i)")
            sleep(1)
        }
    }

3.GCD 

使用最多,虽然也是C语言所写,但是加入了block,使用起来更加灵活.

 OC:

 

(1):异步执行 + 并行队列

//创建一个并行队列
    dispatch_queue_t queue = dispatch_queue_create("标识符", DISPATCH_QUEUE_CONCURRENT);
    
    NSLog(@"---start---");
    
    //使用异步函数封装三个任务
    dispatch_async(queue, ^{
        NSLog(@"任务1---%@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"任务2---%@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"任务3---%@", [NSThread currentThread]);
    });
    
    NSLog(@"---end---");

 

(2):异步执行 + 串行队列

//创建一个串行队列
    dispatch_queue_t queue = dispatch_queue_create("标识符", DISPATCH_QUEUE_SERIAL);
    
    NSLog(@"---start---");
    //使用异步函数封装三个任务
    dispatch_async(queue, ^{
        NSLog(@"任务1---%@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"任务2---%@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"任务3---%@", [NSThread currentThread]);
    });
    NSLog(@"---end---");

(3):同步执行 + 并行队列

//创建一个并行队列
 dispatch_queue_t queue = dispatch_queue_create("标识符", DISPATCH_QUEUE_CONCURRENT);
    
    NSLog(@"---start---");
    //使用同步函数封装三个任务
    dispatch_sync(queue, ^{
        NSLog(@"任务1---%@", [NSThread currentThread]);
    });
    dispatch_sync(queue, ^{
        NSLog(@"任务2---%@", [NSThread currentThread]);
    });
    dispatch_sync(queue, ^{
        NSLog(@"任务3---%@", [NSThread currentThread]);
    });
    NSLog(@"---end---");

  

(4)同步执行+ 串行队列

 

    //创建一个串行队列
    dispatch_queue_t queue = dispatch_queue_create("标识符", DISPATCH_QUEUE_SERIAL);
    
    NSLog(@"---start---");
    //使用异步函数封装三个任务
    dispatch_sync(queue, ^{
        NSLog(@"任务1---%@", [NSThread currentThread]);
    });
    dispatch_sync(queue, ^{
        NSLog(@"任务2---%@", [NSThread currentThread]);
    });
    dispatch_sync(queue, ^{
        NSLog(@"任务3---%@", [NSThread currentThread]);
    });
    NSLog(@"---end---");

 

  

(5)异步执行+主队列

    //获取主队列
    dispatch_queue_t queue = dispatch_get_main_queue();
    
    NSLog(@"---start---");
    //使用异步函数封装三个任务
    dispatch_async(queue, ^{
        NSLog(@"任务1---%@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"任务2---%@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"任务3---%@", [NSThread currentThread]);
    });
    NSLog(@"---end---");

  

(6)同步执行+主队列(死锁)

 

//获取主队列
    dispatch_queue_t queue = dispatch_get_main_queue();
    
    NSLog(@"---start---");
    //使用同步函数封装三个任务
    dispatch_sync(queue, ^{
        NSLog(@"任务1---%@", [NSThread currentThread]);
    });
    dispatch_sync(queue, ^{
        NSLog(@"任务2---%@", [NSThread currentThread]);
    });
    dispatch_sync(queue, ^{
        NSLog(@"任务3---%@", [NSThread currentThread]);
    });
    NSLog(@"---end---");