在Objecttive-C里创建多线程一般有两种方法, 一种是initWithTarget,还有一种是detachNewThreadSelector。
下面是两个实例,创建多线程的实例,支持传递参数.
initWithTarget方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
// // main.m // initWithTarget // Created by exchen on 5/8/15. // Copyright (c) 2015 exchen. All rights reserved. // #import <Foundation/Foundation.h> @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 charchar * 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方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
// // main.m // TestThread // // Created by exchen on 5/8/15. // Copyright (c) 2015 exchen. All rights reserved. // #import <Foundation/Foundation.h> @interface classa : NSObject -(void)StartThread:(NSString *)str; @end @implementation classa -(void)StartThread:(NSString *)str { NSLog(@"%@",str); exit(0); } @end int main(int argc, const charchar * 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; } |
转载请注明:exchen's blog » Objecttive-C 创建多线程