IOS 線程處理 子線程的啟動與結束


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 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM