理解iOS多线程应用的开发以及线程的创建方法

2020-01-14 17:25:43王旭

2.使用NSThread创建线程

复制代码
//
//  YYViewController.m
//
//
//  Created by apple on 14-6-23.
//  Copyright (c) 2014年 itcase. All rights reserved.
//

 

#import "YYViewController.h"
#import <pthread.h>


@interface YYViewController ()
- (IBAction)btnClick;
@end


复制代码
@implementation YYViewController

 

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


//按钮的点击事件
- (IBAction)btnClick {
    //1.获取当前线程
    NSThread *current=[NSThread currentThread];
    //主线程
    NSLog(@"btnClick----%@",current);

    //获取主线程的另外一种方式
   NSThread *main=[NSThread mainThread];
    NSLog(@"主线程-------%@",main);

    //2.执行一些耗时操作
    [self creatNSThread];
//    [self creatNSThread2];
//    [self creatNSThread3];
}

 
/**
 * NSThread创建线程方式1
 * 1> 先创建初始化线程
 * 2> start开启线程
 */
-(void)creatNSThread
{
    NSThread  *thread=[[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"线程A"];
    //为线程设置一个名称
    thread.name=@"线程A";
     //开启线程
    [thread start];
 

    NSThread  *thread2=[[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"线程B"];
    //为线程设置一个名称
    thread2.name=@"线程B";
   //开启线程
    [thread2 start];
}

 
/**
 * NSThread创建线程方式2
*创建完线程直接(自动)启动
 */

-(void)creatNSThread2