多线程
来源:互联网 发布:可视化编程 编辑:程序博客网 时间:2024/04/30 23:43
使用系统提供的创建子线程的方法,自动开启.对于耗时的工作,我们需要将工作交给子线程去做.主线程来执行界面的加载和处理用户的交互.这样我们就可以提高用户的体验度
对线程而言,我们并没有创建过线程,而是将任务添加在队列里面.我们需要做的就是管理好队列.
对于多线程而言,我们必须要记得队列分为并行队列和串行队列,其中可以处理的任务又分为同步任务和异步任务,如果由并行队列执行同步任务,则由主线程执行同步任务,若是并行队列执行异步任务,则是由子线程执行异步任务.如果是串行队列执行同步任务的,则是执行同步任务的,如果是串行队列执行异步任务,则还是执行异步任务的.
<span style="font-size:24px;"> NSLog(@"thread = %@ isMainThread = %d",[NSThread currentThread],[NSThread isMainThread]);</span>
[NSThread detachNewThreadSelector:@selector(task1) toTarget:self withObject:nil];// withObject代表的是@selector(task1)中task1方法所带的参数
//2手动创建子线程// NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(task1) object:nil];// [thread start];// [thread release];
手动创建的线程一定要记得开启.
3 使用NSobject
<span style="font-size:24px;"> [self performSelectorInBackground:@selector(downLoadImage) withObject:nil]; [self performSelectorInBackground:@selector(timerAction) withObject:nil];</span>
- (void)downLoadImage{ @autoreleasepool { NSString *urlSTr = @"http://image.zcool.com.cn/56/13/1308200901454.jpg"; NSURL *url = [NSURL URLWithString:urlSTr]; //从网络请求资源都是二进制数据 //内存泄露,原因:在子线程执行的方法中系统默认不会加自动释放池 NSData *imageData = [NSData dataWithContentsOfURL:url]; [self performSelectorOnMainThread:@selector(loadImage:) withObject:imageData waitUntilDone:YES]; } }
- (void)timerAction{ //子线程中存在事件循环处理机制(Runloop,但是默认状态是关闭的,因此需要手动开启) [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(otuPutAction) userInfo:nil repeats:YES]; //打开runloop:(子线程默认是有runLoop的,但是默认是关闭的) [[NSRunLoop currentRunLoop] run];}
<span style="font-size:18px;"> //4 线程队列: NSOperationQueue //1⃣️ 创建任务 NSInvocationOperation *operation1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(task2:) object:@"cuijin"]; NSInvocationOperation *operation2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(task3:) object:@"liyang"]; //2⃣️ 创建队列 NSOperationQueue *queue = [[NSOperationQueue alloc]init]; //3⃣️ 添加任务 [queue addOperation:operation1]; [queue addOperation:operation2]; //4⃣️ 释放所有权 [queue release]; [operation2 release]; [operation1 release];</span>
0 0
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- 多线程
- API 简单理解
- ProGuard Version5.2(4.2)Manual-->Limitations
- SDN的两种方式分析
- 我的第一份工作-檀木科技
- headers already sent
- 多线程
- android sqlite 的创建与使用,sqlite自定义框架。
- C++静态库编译
- android之Widget
- mysql分表和表分区详解
- 数据结构之动态搜索&平衡二叉树(ADT)
- Android Studio 虚拟机错误
- 第四讲:标签页效果
- Ping of Death 攻击 和 ICMP 风暴