ios 异步多线程 获取数据

- - (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次
- });
ios 异步多线程 获取数据的更多相关文章
- 李洪强iOS开发-网络新闻获取数据思路回顾
李洪强iOS开发-网络新闻获取数据思路回顾 01 创建一个继承自AFHTTPSessionManager的工具类:LHQNetworkTool 用来发送网络请求获取数据 1.1 定义类方法返回单例对 ...
- ajax异步请求获取数据,实现滚动数字的效果。
BackgroundPositionAnimate.js下载 需要导入的js: <script type="text/javascript" src="js/jqu ...
- 16 react 发送异步请求获取数据 和 使用Redux-thunk中间件进行 ajax 请求发送
1.发送异步请求获取数据 1.引入 axios ( 使用 yarn add axios 进行安装 ) import axios from 'axios'; 2. 模拟 在元素完成挂载后加载数据 并初始 ...
- Salesforce LWC学习(十四) Continuation进行异步callout获取数据
本篇参考: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.apex_continua ...
- python3 多线程获取数据实例
import requestsimport jsonfrom retrying import retryfrom lxml import etreefrom queue import Queueimp ...
- uni-app如何解决在for循环里调用异步请求获取数据顺序混乱问题?
总结/朱季谦 先前有一次做uni-app的js接口对接时,遇到过这样的情况,在for循环里,调用一个异步请求时,返回来的值顺序是乱的,因此,在以下的代码里,push到数组里的值,每次的顺序可能都是不一 ...
- IOS开发---菜鸟学习之路--(十三)-利用MBProgressHUD进行异步获取数据
本章将介绍如何利用MBProgressHUD实现异步处理数据. 其实我本来只是像实现一个加载数据时提示框的效果,然后问了学长知道了这个类,然后就使用了 接着就发现了一个“BUG” 再然后就发现原来MB ...
- IOS开发---菜鸟学习之路--(十二)-利用ASIHTTPRequest进行异步获取数据
想要实现异步获取的话我这边了解过来有两个非常简单的方式 一个是利用ASIHTTPRequest来实现异步获取数据 另一个则是利用MBProgressHUD来实现异步获取数据 本章就先来讲解如何利用AS ...
- HBase 高性能获取数据(多线程批量式解决办法) + MySQL和HBase性能测试比较
摘要: 在前篇博客里已经讲述了通过一个自定义 HBase Filter来获取数据的办法,在末尾指出此办法的性能是不能满足应用要求的,很显然对于如此成熟的HBase来说,高性能获取数据应该不是问题. ...
随机推荐
- isKindOfClass、isMemberOfClass的区别
两者都能检测一个对象是否是某个类的成员,两者的区别是:isKindOfClass 不但可以用来确定一个对象是否是一个类的成员,也可以用来确定一个对象是否是派生自该类的类的成员.isMemberOfCl ...
- C#总结(一)
学C#也有两年多了,发现如果不总结一下,很多C#的知识都会忘掉,所以希望写这系列的文章来总结一下C#的基础知识.如果有写错或者不足的地方,希望可以提出纠正. C#可以说是依附在.NET Framewo ...
- 保存BASE64编码图片
1.前端上传用户图片时,一些K数较小图片,头像图标等 .以bass64编码后的字符串传到服务器. 2.服务器接收并保留到本地. // 页面上点击保存 $.post('/imgupload/save', ...
- mongodb的连接问题,绑定IP惹的祸
刚刚安装好了 mongodb .对着 mongodb in action上的例子敲了下面的代码: public class TestDBConnect { @Test public void test ...
- Java之集合类
出处:http://blog.csdn.net/zhangerqing 一.集合类简介 数组是很常用的一种的数据结构,我们用它可以满足很多的功能,但是,有时我们会遇到如下这样的问题: 1.我们需要该容 ...
- Django的 select_related 和 prefetch_related 函数对 QuerySet 查询的优化(三)
4.一些实例 如果我们想要获得所有家乡是湖北的人,最无脑的做法是先获得湖北省,再获得湖北的所有城市,最后获得故乡是这个城市的人.就像这样: 1 2 3 4 5 >>> hb = Pr ...
- [POJ] 3461 Oulipo [KMP算法]
Oulipo Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 23667 Accepted: 9492 Descripti ...
- VC6-Win7下VC++6.0打开多个工程的设置
在Win7操作系统下,如果是以Administrator登陆,则VC6.0打开工程文件的时候,不能同时打开多个工程文件,后打开的工程会将前一个工程close掉,这样,VC6.0只能出现一个进程.在xp ...
- YII学习笔记-登录后的session的总结
在YII框架的默认的登录后的session数据是id,name,__states这三个数据. 在搭配好YII框架环境后,可以使用admin/admin,来登录系统.如果在protected/views ...
- ASP.NET MVC3快速入门——第四节、添加一个模型
在本节中我们将追加一些类来管理数据库中的电影.这些类将成为我们的MVC应用程序中的“模型”部分.我们将使用一个.NET Framework的被称之为“Entiry Framework”的数据访问技术来 ...