IOS多线程(NSThread)
1.创建方法
使用NSThread创建线程主要有两个个方法,分别如下
-
NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething:) object:nil];
[myThread start];
- [NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:nil];
这两种方式的区别在于:
前一种方式尽管alloc了一个新Thread,但需要手动调用start方法来启动线程。这点与Java创建线程的方式相似。第二种方式,与上述做法1使用NSObject的类方法performSelectorInBackground:withObject:是一样的;第二种方式的可以在start真正创建线程之前对其进行设置,比如设置线程的优先级。第二种调用就会立即创建一个线程并执行selector方法。
使用NSThread创建线程时,要在执行的方法中自行管理内存,否则会有内存溢出警告。
- (void)doSomething:(id)sender
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[pool release];
}
2.线程间的通讯
与主线程通讯
[self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];
与指定的线程通讯
[viewDelegate performSelector:@selector(someMethod)
onThread:[NSThread mainThread] withObject:nil waitUntilDone:NO]
3.线程同步
线程同步主要用
NSCondition 和 NSLock
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; tickets = 100; count = 0; theLock = [[NSLock alloc] init]; // 锁对象 ticketsCondition = [[NSCondition alloc] init]; ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil]; [ticketsThreadone setName:@"Thread-1"]; [ticketsThreadone start]; ticketsThreadtwo = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil]; [ticketsThreadtwo setName:@"Thread-2"]; [ticketsThreadtwo start]; NSThread *ticketsThreadthree = [[NSThread alloc] initWithTarget:self selector:@selector(run3) object:nil]; [ticketsThreadthree setName:@"Thread-3"]; [ticketsThreadthree start]; self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. [self.window makeKeyAndVisible]; return YES; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; } -(void)run3 { while (YES) { [ticketsCondition lock]; [NSThread sleepForTimeInterval:3]; [ticketsCondition signal]; [ticketsCondition unlock]; } } - (void)run { while (TRUE) { // 上锁 [ticketsCondition lock]; [ticketsCondition wait]; [theLock lock]; if(tickets >= 0){ [NSThread sleepForTimeInterval:0.09]; count = 100 - tickets; NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]); tickets--; }else{ break; } [theLock unlock]; [ticketsCondition unlock]; } }