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

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