iOS开发用的线程发展主要有三个阶段
NSTread、NSOpoperation、GCD
这篇文章主要讲解基础篇NSTread
一、NSTread的创建
//NSTread 创建方式
NSThread *oneThread = [[NSThread alloc] initWithTarget:self selector:@selector(test:) object:kurl];
//设置线程优先级
[oneThread setThreadPriority:0.5];
//设置线程名称
[oneThread setName:@"oneThread"];
//线程开始
[oneThread start];
//线程延时 阻塞
[NSThread sleepForTimeInterval:60];
//线程取消 取消可以再次开启 退出不能开启
[oneThread cancel];
//线程退出
[NSThread exit];
//另外一种创建方式,创建成功自动运行
[NSThread detachNewThreadSelector:@selector(test) toTarget:self withObject:kurl];
//获取当前线程
NSThread *thread = [NSThread currentThread];
//判断是否为主线程
BOOL result = oneThread.isMainThread;
//更新UI都需要主线程来操作
[self performSelectorOnMainThread:@selector(updateUI:) withObject:img waitUntilDone:YES];
//更新其他线程执行操作
performSelector:onThread:withObject:waitUntilDone:
上面写到的只是一小部分,对于线程的操作控制基本上能想到的都会有对应的方法。
二、线程锁问题
NSLock:常用的锁类 基本使用方法 调用统一方法 操作同一对象 简单应用
- (void)run{
while (TRUE) {
// 上锁
[_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];
}
}
iOS提供一种简单编写锁事件的方式 @synchronized(anObj) anObj这是
-(void)run:(nsstring *) anObj{
@synchronized(anObj)
{
代码块需要加锁的
}
}
总结
NSThread并不是主流的多线程使用方式可以作为了解,回调主线程、一些简单单一的线程可以使用。