设为首页 加入收藏

TOP

Objecttive-C 创建多线程
2015-07-16 12:04:14 来源: 作者: 【 】 浏览:107
Tags:Objecttive-C 创建 线程

在Objecttive-C里创建多线程一般有两种方法, 一种是initWithTarget,还有一种是detachNewThreadSelector。

下面是两个实例,创建多线程的实例,支持传递参数.

?

initWithTarget方式

?

//
//  main.m
//  initWithTarget
//  Created by exchen on 5/8/15.
//  Copyright (c) 2015 exchen. All rights reserved.
//

#import 
  
   

@interface classa : NSObject

-(void)StartThread:(NSString *)str;

@end

@implementation classa

-(void)StartThread:(NSString *)str
{ 
    sleep(3);
    
    NSLog(str);
   
    exit(0);
}

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");
    }
    
    classa *a = [[classa alloc] init];
    NSThread *thread = [[NSThread alloc] initWithTarget:a selector:@selector(StartThread:) object:@"Start"];
    [thread start];
    
    sleep(5);
    return 0;
}
  

detachNewThreadSelector方式

?

//
//  main.m
//  TestThread
//
//  Created by exchen on 5/8/15.
//  Copyright (c) 2015 exchen. All rights reserved.
//
#import 
  
   

@interface classa : NSObject

-(void)StartThread:(NSString *)str;

@end

@implementation classa

-(void)StartThread:(NSString *)str
{
    NSLog(@"%@",str);
    exit(0);
}

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");
        
        classa *a = [[classa alloc] init];
        
        [NSThread detachNewThreadSelector:@selector(StartThread:) toTarget:a withObject:@"Start"];
        
        sleep(5);
        
    }
    return 0;
}
  


?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C语言提高之――指针表达式 下一篇C语言笔记之printf()函数

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: