NSThread起线程用法2

 NSThread是起线程的主角,大部分时候我们使用这个类。

建一个view-based application.


在viewcontroller.h中

@interface tNSThreadViewController : UIViewController {

    NSThread *t1;
BOOL bExit;
}
@property BOOL bExit;
- (IBAction)checkit:(id)sender;
- (IBAction)start2:(id)sender;
- (IBAction)start:(id)sender;
-(void)doSomething:(id)data;
@end



在viewcontroller.m中



#import "tNSThreadViewController.h"

@implementation tNSThreadViewController
@synthesize bExit;
-(void)doSomething:(id)data
{

/*[[t1 threadDictionary] setObject:@"kkk" forKey:@"k11"];
NSMutableDictionary * md = [t1 threadDictionary];
NSString *t = [md objectForKey:@"k11"];
NSLog(@"%@", t);
NSLog(@"kasdkf");
*/
//NSString *d = (NSString *)data;
//NSLog(@"%@",d);
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *s = [NSString stringWithFormat:@"%d",1];
NSLog(@"%@",s);
while (true) {
[NSThread sleepForTimeInterval:0.5];
NSLog(@"IN thread");
tNSThreadViewController *inputData = (tNSThreadViewController *)data;
if(inputData.bExit)
break;
}
[pool release];


}


- (void)viewDidLoad
{
bExit = NO;
[super viewDidLoad];
}



- (IBAction)checkit:(id)sender {
bExit = YES;
if([NSThread isMultiThreaded]) {
NSLog(@"it is multi thread");
}
else {
NSLog(@"it is not multi thread");
}
}

- (IBAction)start2:(id)sender {
if(t1 != nil)
{

[t1 release];
t1 = nil;
}
t1 = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething:) object:self];
[t1 setStackSize:1024*1024];
[t1 setThreadPriority:0.5];

[t1 start];

/*NSThread *t2 = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething:) object:@"2"];
[t2 setStackSize:1024*1024];
[t2 setThreadPriority:0.9];

[t2 start];
*/

}

- (IBAction)start:(id)sender {
//[self performSelectorInBackground:<#(SEL)#> withObject:<#(id)#>
[NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:nil];
}
@end

最后需要说明的是,iOS应用的主线程的栈大小缺省为1M,其他线程的栈大小缺省为512K,很多网上文章说,不能调这个大小,那是以讹传讹,如何调大小,请看我的代码。

posted @ 2012-03-29 11:39  wujian1360  阅读(1551)  评论(0编辑  收藏  举报