多线程 之 NSThread 简单操作适合初学者


/**   run<NSThread: 0x712d5b0>{name = (null), num = 1}

 num 1 是主线程 其他就是创建的子线程

 

 使用NSThread 的优缺点

 1 优点:NSThread 比其他多线程方案较轻量级,更直观地控制线程对象

 2 缺点:需要管理线程生命周期,同步加锁问题,会导致一定的性能开销

 

 */


- (void)viewDidLoad

{

    [super viewDidLoad];

    //创建线程方式

//  NSThread *thread = [NSThread currentThread];

//  NSThread *thread = [NSThread mainThread];


    [self currentThread6];

  

    

}


//在当前线程中执行创建线程

- (void)currentThread6

{

    [self performSelector:@selector(run) withObject:nil];

}


//主线程创建了一条线程

- (void)currentThread5

{

    [self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];

}


//指定的线程创建了一条线程

- (void)currentThread4

{

   NSThread *thread =  [NSThread mainThread];

    [self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:YES];

    

}


//隐士创建一条线程

- (void)currentThread3

{

    //在后台运行调用创建线程

    [self performSelectorInBackground:@selector(run) withObject:nil];

    

}


//执行完方法后启动一条新线程 静态方法 detachNewThreadSelector 没有返回值所以不需要启动线程

- (void)currentThread2

{

    [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];

    //线程延迟2秒调用当前主线程

//    [NSThread sleepForTimeInterval:2];

    //根据当前的时间停止2

    NSDate *date = [NSDate dateWithTimeInterval:2 sinceDate:[NSDate date]];

    [NSThread sleepUntilDate:date];

    NSLog(@"currentThread2");

    

}


//执行完方法后启动一条新线程 动态方法 initWithTarget 需要启动线程

- (void)currentThread1

{

    //创建线程 调用线程方法

    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];

    NSLog(@"viewDidLoad%@",thread);

    

    //开启线程

    [thread start];

}


//线程

- (void)run

{

    //创建了一条线程

 NSThread *thread =  [NSThread currentThread];

    NSLog(@"run%@",thread);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值