Xcode7.2NSThread、GCD多线程创建及简单使用

NSThreadGCD多线程创建及简单使用

【PS】:NSOpretion创建多线程的方式不常使用,本篇不做介绍。

一、NSThread创建多线程

1、线程创建方法


方法一:

-(void)nsThreadCreat_Method1
{
    //    NSLog(@"-----第一种:NSThread线程------");
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(print50Number) object:nil];
    thread.name = @"NSThread创建的子线程";
    [thread start];
}

方法二:

-(void)nsThreadCreat_Method2
{
    //    NSLog(@"-----第二种:NSThread线程------");
    [self performSelectorInBackground:@selector(print50Number) withObject:nil];
}

方法三:

-(void)nsThreadCreat_Method3
{
    //    NSLog(@"-----第三种:NSThread线程------");
    [NSThread detachNewThreadSelector:@selector(print50Number) toTarget:self withObject:nil];
}


2、利用- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event方法调用以上3中创建方法逐个测试。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self nsThreadCreat_Method1];
    [self nsThreadCreat_Method2];
    [self nsThreadCreat_Method3];
}


3、NSTread睡眠方法*

[NSThread sleepForTimeInterval:2];//线程睡眠2秒


二、GCD创建多线程

【重点】 GCD线程创建方法


注意GCD是使用多线程开发最常用的方式,NSThread和NSOpretion不常用!

-(void)gcdAsync_globalQueueMethod
{
//    GCD异步方法 --- 使用全局并发队列
    dispatch_queue_t queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0);
    dispatch_async(queue, ^{
        NSLog(@"-----当前线程------%@", [NSThread currentThread]);
    });
}

详细代码:

//  Created by djb on 15/12/25.
//  Copyright © 2015年 bao. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self nsThreadCreat_Method1];
    [self nsThreadCreat_Method2];
    [self nsThreadCreat_Method3];
}

-(void)print50Number
{
    [NSThread sleepForTimeInterval:2];//线程睡眠2秒
    NSLog(@"当前线程==%@", [NSThread currentThread]);
    for (int i=0; i<3; i++) {
        NSLog(@"-----%d次打印--", i);
    }
}

-(void)nsThreadCreat_Method1
{
    //    NSLog(@"-----第一种:NSThread线程------");
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(print50Number) object:nil];
    thread.name = @"NSThread创建的子线程";
    [thread start];
}

-(void)nsThreadCreat_Method2
{
    //    NSLog(@"-----第二种:NSThread线程------");
    [self performSelectorInBackground:@selector(print50Number) withObject:nil];
}

-(void)nsThreadCreat_Method3
{
    //    NSLog(@"-----第三种:NSThread线程------");
    [NSThread detachNewThreadSelector:@selector(print50Number) toTarget:self withObject:nil];
}


-(void)gcdAsync_globalQueueMethod
{
//    GCD异步方法 --- 使用全局并发队列
    dispatch_queue_t queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0);
    dispatch_async(queue, ^{
        NSLog(@"-----当前线程------%@", [NSThread currentThread]);
    });
}

@end

如有错误,请及时指出!谢谢





你可能感兴趣的:(iOS,苹果开发)