mac下多線程實現處理

mac下線程開啓
注意:
1、新的線程必須考慮設立一個autorelease池處理自動釋放的代碼。
模版如下:
NSAutoreleasePool *pool = [ [ NSAutoreleasePool alloc ] init ]; 
[code here] 
[pool release]; 
如果你能確保自己寫的代碼自己申請,自己釋放的話,不使用autorelease的對象,那麼建議:採用自己釋放的方式
2、
下來是Run Loop的使用場合:
1. 使用port或是自定義的input source來和其他線程進行通信
2. 在線程(非主線程)中使用timer
3. 使用 performSelector...系列(如performSelectorOnThread, ...)
4. 使用線程執行週期性工作
3、說哈線程和NSTimer
http://3426724.blog.51cto.com/3416724/747650
參考這地址,進行實踐
線程執行實現:
- (void)thread3
{
    NSLog(@"t3 = %@ ,isMainThread = %d ,isMulti = %d" ,[NSThread currentThread] ,[NSThread isMainThread] ,[NSThread isMultiThreaded]);
    
    while (YES)
    {        
        [NSThread sleepForTimeInterval:3];
        
        break;
    }
    
    self->btnBind.hidden = NO;    
    
    return;
}
手工啓動線程:
- (IBAction)bindEmail:(id)sender
{
    [self Test039];
    
    NSLog(@"over");
}
線程啓動如下:
- (void)Test038
{
    /// 方法2 能啓動,timer事件正常完成下timer退出,timer啓動線程能釋放,thread3作爲非主線程函數執行
    NSAutoreleasePool *timerNPool = [[NSAutoreleasePool alloc] init];
    NSRunLoop *runloop = [NSRunLoop currentRunLoop];
    [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(thread3) userInfo:nil repeats:NO];
    [runloop run];
    [timerNPool release];
    
    /// 方法3,結論:啓動thread3,作爲主線程的一個函數執行
//    NSTimer *timer1 = [NSTimer timerWithTimeInterval:15 target:self selector:@selector(thread3) userInfo:nil repeats:NO];
//    [[NSRunLoop mainRunLoop] addTimer:timer1 forMode:NSDefaultRunLoopMode];
}
- (void)Test039
{
    // 啓動一個線程,線程對應使用timer(未使用方法2和方法3,直接timer)。結論:無法啓動timer
    //[NSThread detachNewThreadSelector:@selector(Test038) toTarget:self withObject:nil];
    [NSThreadManager StartNewThreadWithTarget:self selector:@selector(Test038) object:nil];

}

轉自:http://www.cnblogs.com/GoGoagg/archive/2012/03/31/2426475.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章