iOS多线程编程技术之NSThread、Cocoa NSOperation、GCD
iOS有三种多线程编程的技术,分别是:NSThread 、Cocoa NSOperation 、GCD。 这三种编程方式从上到下,抽象度层次是从低到高的,抽象度越高的使用越简单,也是Apple最推荐使用的。
“”
iOSGCD多线程编程NSThreadCocoa NSOperation
- - (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument
- + (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument
- 1、[NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:nil];
- 2、NSThread* myThread = [[NSThread alloc] initWithTarget:self
- selector:@selector(doSomething:)
- object:nil];
- [myThread start];
- [Obj performSelectorInBackground:@selector(doSomething) withObject:nil];
- //
- // ViewController.m
- // NSThreadDemo
- //
- // Created by rongfzh on 12-9-23.
- // Copyright (c) 2012年 rongfzh. All rights reserved.
- //
- #import "ViewController.h"
- #define kURL @"http://avatar.csdn.net/2/C/D/1_totogo2010.jpg"
- @interface ViewController ()
- @end
- @implementation ViewController
- -(void)downloadImage:(NSString *) url{
- NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
- UIImage *image = [[UIImage alloc]initWithData:data];
- if(image == nil){
- }else{
- [self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];
- }
- }
- -(void)updateUI:(UIImage*) image{
- self.imageView.image = image;
- }
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- // [NSThread detachNewThreadSelector:@selector(downloadImage:) toTarget:self withObject:kURL];
- NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(downloadImage:) object:kURL];
- [thread start];
- }
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- @end
- [self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];
- performSelector:onThread:withObject:waitUntilDone:
- #import <UIKit/UIKit.h>
- @class ViewController;
- @interface AppDelegate : UIResponder <UIApplicationDelegate>
- {
- int tickets;
- int count;
- NSThread* ticketsThreadone;
- NSThread* ticketsThreadtwo;
- NSCondition* ticketsCondition;
- NSLock *theLock;
- }
- @property (strong, nonatomic) UIWindow *window;
- @property (strong, nonatomic) ViewController *viewController;
- @end
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
- {
- 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];
- self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
- // Override point for customization after application launch.
- self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
- self.window.rootViewController = self.viewController;
- [self.window makeKeyAndVisible];
- return YES;
- }
- - (void)run{
- while (TRUE) {
- // 上锁
- // [ticketsCondition lock];
- [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];
- }
- }
- #import "AppDelegate.h"
- #import "ViewController.h"
- @implementation AppDelegate
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
- {
- 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.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
- self.window.rootViewController = self.viewController;
- [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];
- }
- }
- - (void)doSomeThing:(id)anObj
- {
- @synchronized(anObj)
- {
- // Everything between the braces is protected by the @synchronized directive.
- }
- }
- #import "ViewController.h"
- #define kURL @"http://avatar.csdn.net/2/C/D/1_totogo2010.jpg"
- @interface ViewController ()
- @end
- @implementation ViewController
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self
- selector:@selector(downloadImage:)
- object:kURL];
- NSOperationQueue *queue = [[NSOperationQueue alloc]init];
- [queue addOperation:operation];
- // Do any additional setup after loading the view, typically from a nib.
- }
- -(void)downloadImage:(NSString *)url{
- NSLog(@"url:%@", url);
- NSURL *nsUrl = [NSURL URLWithString:url];
- NSData *data = [[NSData alloc]initWithContentsOfURL:nsUrl];
- UIImage * image = [[UIImage alloc]initWithData:data];
- [self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];
- }
- -(void)updateUI:(UIImage*) image{
- self.imageView.image = image;
- }
- [queue setMaxConcurrentOperationCount:5];
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- // 耗时的操作
- dispatch_async(dispatch_get_main_queue(), ^{
- // 更新界面
- });
- });
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- NSURL * url = [NSURL URLWithString:@"http://avatar.csdn.net/2/C/D/1_totogo2010.jpg"];
- NSData * data = [[NSData alloc]initWithContentsOfURL:url];
- UIImage *image = [[UIImage alloc]initWithData:data];
- if (data != nil) {
- dispatch_async(dispatch_get_main_queue(), ^{
- self.imageView.image = image;
- });
- }
- });
- dispatch_queue_t globalQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
- dispatch_queue_t mainQ = dispatch_get_main_queue();
- dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
- dispatch_group_t group = dispatch_group_create();
- dispatch_group_async(group, queue, ^{
- [NSThread sleepForTimeInterval:1];
- NSLog(@"group1");
- });
- dispatch_group_async(group, queue, ^{
- [NSThread sleepForTimeInterval:2];
- NSLog(@"group2");
- });
- dispatch_group_async(group, queue, ^{
- [NSThread sleepForTimeInterval:3];
- NSLog(@"group3");
- });
- dispatch_group_notify(group, dispatch_get_main_queue(), ^{
- NSLog(@"updateUi");
- });
- dispatch_release(group);
- 2012-09-25 16:04:16.737 gcdTest[43328:11303] group1
- 2012-09-25 16:04:17.738 gcdTest[43328:12a1b] group2
- 2012-09-25 16:04:18.738 gcdTest[43328:13003] group3
- 2012-09-25 16:04:18.739 gcdTest[43328:f803] updateUi
- dispatch_queue_t queue = dispatch_queue_create("gcdtest.rongfzh.yc", DISPATCH_QUEUE_CONCURRENT);
- dispatch_async(queue, ^{
- [NSThread sleepForTimeInterval:2];
- NSLog(@"dispatch_async1");
- });
- dispatch_async(queue, ^{
- [NSThread sleepForTimeInterval:4];
- NSLog(@"dispatch_async2");
- });
- dispatch_barrier_async(queue, ^{
- NSLog(@"dispatch_barrier_async");
- [NSThread sleepForTimeInterval:4];
- });
- dispatch_async(queue, ^{
- [NSThread sleepForTimeInterval:1];
- NSLog(@"dispatch_async3");
- });
- 2012-09-25 16:20:33.967 gcdTest[45547:11203] dispatch_async1
- 2012-09-25 16:20:35.967 gcdTest[45547:11303] dispatch_async2
- 2012-09-25 16:20:35.967 gcdTest[45547:11303] dispatch_barrier_async
- 2012-09-25 16:20:40.970 gcdTest[45547:11303] dispatch_async3
- dispatch_apply(5, globalQ, ^(size_t index) {
- // 执行5次
- });
转载于:https://www.cnblogs.com/fengmin/p/5015842.html
iOS多线程编程技术之NSThread、Cocoa NSOperation、GCD相关推荐
- 【转】iOS多线程编程技术之NSThread、Cocoa NSOperation、GCD
转自容芳志的博客 简介 iOS有三种多线程编程的技术,分别是: (一)NSThread (二)Cocoa NSOperation (三)GCD(全称:Grand Central Dispatch) ...
- iOS开发-多线程编程技术(Thread、Cocoa operations、GCD)
简介 在软件开发中,多线程编程技术被广泛应用,相信多线程任务对我们来说已经不再陌生了.有了多线程技术,我们可以同做多个事情,而不是一个一个任务地进行.比如:前端和后台作交互.大任务(需要耗费一定的时间 ...
- java超线程_超线程多核心下Java多线程编程技术分析
在学习编程的过程中,我觉得不止要获得课本的知识,更多的是通过学习技术知识提高解决问题的能力,这样我们才能走在最前方,本文主要讲述超线程多核心下Java多线程编程技术分析,更多Java专业知识,广州疯狂 ...
- 漫谈C++ Builder多线程编程技术
漫谈C++ Builder多线程编程技术 http://tech.163.com/school · 2005-05-31 10:52:34 · 来源: 计算机与信息技术 摘 要:本文简单介绍了Wind ...
- Windows下多线程编程技术及其实现
本文首先讨论16位Windows下不具备的线程的概念,然后着重讲述在32位Windows 95环境下多线程的编程技术,最后给出利用该技术的一个实例,即基于Windows95下TCP/IP的可视电话的实 ...
- Android开发中的多线程编程技术
Android开发中的多线程编程技术 [IT168技术]多线程这个令人生畏的"洪水猛兽",很多人谈起多线程都心存畏惧.在Android开发过程中,多线程真的很难吗?多线程程序的&q ...
- 多线程编程技术开发资料
多线程编程技术开发资料 目录 Win32 多线程的性能(1)... 1 Win32 多线程的性能(2)... 10 关于多线程的一些细节... 23 用VC++5.0 实 现 多 线 程 的 调 度 ...
- iOS多线程编程的知识梳理
多线程编程也称之为并发编程,由于其作用大,有比较多的理论知识,因此在面试中也是受到面试官的青睐.在日常项目开发中,至少网络请求上是需要使用到多线程知识的,虽然使用第三方的框架比如AFNetworkin ...
- Android 开发中的多线程编程技术
此文章来自"Intel Software"应用开发 多线程这个令人生畏的"洪水猛兽",很多人谈起多线程都心存畏惧.在Android开发过程中,多线程真的很难吗? ...
最新文章
- data-参数说明(模态弹出窗的使用)
- 一个电脑白痴与黑客的对话
- shell 指令集锦
- 我的HTTP/3学习笔记
- 两个list关联合并_算法分享---两个有序链表的合并(C语言)
- 关于SharePoint部署Webpart的十个必读链接(downmoon)
- 关于求职简历的碎碎念。
- C++ STL : SGI-STL空间配置器源码剖析
- 时间序列(七): 高冷贵族: 隐马尔可夫模型
- ajax大数据导入的一系列问题处理
- C语言麻将递归,C++数据结构与算法——麻将胡牌算法(二:完全胡牌算法)
- 《HTML5游戏编程核心技术与实战》——2.5 绘制文字
- vue调用函数怎么传参_Vue(非)父子组件的传值以及方法调用
- LR中并发用户和集合点
- 2018药品目录匹配_本位码_众联社本位码匹配工具2018版破解版
- 微信小程序 自定义标题栏
- 手机java淘汰_极客修:对手并不止安卓!这些年iOS竟然把这么多手机系统淘汰掉了...
- 移动安全规范 — 1 -WIFI连接安全规范
- Markdown语法之html内嵌样式
- 【python爬虫】js逆向:空气质量在线平台,解决反调试,加密
热门文章
- asp.net,Ajax发送异步请求后台修改数据
- flex连接mysql,flex对数据库(sqlite)的操作
- Tomcat启动提示At least one JAR was scanned for TLDs yet contained no TLDs
- IE8的的文本模式怎么固定
- Java常用的几个Json库
- 从零开始的网站搭建,服务器与域名管理
- 【codevs1231】最优布线问题
- 查看 java heapspace_Java heap space 问题查找
- 基于matlab单目视觉焊缝跟踪系统,基于激光线结构光3D视觉的机器人轨迹跟踪方法与应用...
- 第八章节 文件操作一 (文件对话框)