IOS 线程处理 子线程的启动与结束

本文介绍了在iOS开发中如何使用NSThread进行多线程编程,包括创建子线程的方法及如何控制子线程运行和停止。并通过一个示例程序详细展示了如何在主线程中启动子线程,并在子线程中执行循环任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

IOS中,如果要在主线程中启动一个子线程,可以又两种方法:

[cpp] 
[NSThread detachNewThreadSelector:@selector(myThreadMainMethod:) toTarget:self withObject:nil]; 
这是在cocoa早期提供的方法,因此你可以在任何版本的ios和mac上调用此方法。
在 OS X v10.5(or later)和IOS中,苹果又提供了一种方法,可以允许你获得你的thread句柄,并且更方便的让主线程控制子线程。

[cpp] 
NSThread* myThread = [[NSThread alloc] initWithTarget:self 
                                        selector:@selector(myThreadMainMethod:) 
                                        object:nil]; 
[myThread start];  // Actually create the thread 

如果要停止子线程,有两种方法:
第一种,是在子线程中执行:

[cpp] 
[NSThread exit]; 

另一种是在主线程执行:
[cpp]
[myThread cancel];  
要注意的是,[mThread cancel]; 并不能exit线程,只是标记为canceled,但线程并没有死掉。加入你在子线程中执行了一个循环,则cancel后,循环还在继续,你需要在循环的条件判断中加入 !mThread.isCancelled 来判断子线程是否已经被cancel来决定是否继续循环。

下面是我的一个测试demo,可以参考一下:
[cpp] 
@synthesize mThread; 
- (void)viewDidLoad 

    [super viewDidLoad]; 
     
    NSLog(@"main thread:%@",[NSThread currentThread]); 
     mThread=[[NSThread alloc] initWithTarget:self selector:@selector(subThreadMethod) object:nil]; 
    [NSThread detachNewThreadSelector:@selector(performMethod) toTarget:self withObject:nil]; 
  

-(void)subThreadMethod{ 
    int i=1; 
    while (i++>0 && ![[NSThread currentThread]isCancelled]) { 
        NSLog(@"subthread i:%d ,thread:%@",i,[NSThread currentThread]); 
    }   

 
- (IBAction)startThread:(id)sender { 
    NSLog(@"startThread...."); 
    [mThread start]; 

 
- (IBAction)stopThread:(id)sender { 
    NSLog(@"mThread.isCancelled: %d",mThread.isCancelled); 
    if (!mThread.isCancelled) { 
        [mThread cancel]; 
//        [mThread exit]; //exit 是类方法,不可以用在对象上 
    } 

 
- (IBAction)performOnSubThread:(id)sender { 
    //在子线程调用方法 
     [self performSelector:@selector(performMethod) onThread:mThread withObject:nil waitUntilDone:NO]; 

-(void)performMethod{ 
    NSLog(@"performMethod.... thread:%@",[NSThread currentThread]);     

@end 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值