使用NSThread起线程

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

由于本人macbook暂时不能用,所以这里只贴出代码:

建一个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)dealloc
{
[super dealloc];
}

- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
bExit = NO;
[super viewDidLoad];
}


- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (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,很多网上文章说,不能调这个大小,那是以讹传讹,如何调大小,请看我的代码。

你可能感兴趣的:(thread)