java - 发送10个网络请求,然后再接收到所有回应之后执行后续操作,如何实现?
天蓬老师
天蓬老师 2017-04-17 16:15:12
0
21
1604

我想到的

for iOS
1.用dispatch_group实现
2.用RunLoop实现   

还有没有其他的比较好的实现方式,求关于并发编程的文章.

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(21)
伊谢尔伦

Then network requests are all asynchronous, are they handled in the same way?

迷茫

Build a block or closure. Send a network request and call itself in completionHandler to send the next request.

迷茫

Android definitely RxJava. iOS RxSwift?

Ty80

dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
[request1 completed:^(BOOL sucess, id response){

dispatch_grpup_leave(group);

}];

dispatch_group_enter(group);
[request2 completed:^(BOOL sucess, id response){

dispatch_grpup_leave(group);

}];

dispatch_group_enter(group);
[request3 completed:^(BOOL sucess, id response){

dispatch_grpup_leave(group);

}];

dispatch_group_enter(group);
[request4 completed:^(BOOL sucess, id response){

dispatch_grpup_leave(group);

}];
.
.
.
.

dispatch_group_notify(group, dispatch_get_main_queue(), ^{

[do something];

});

黄舟

I feel it is better to use GCD, because it can always be in c/c++ code

小葫芦

Use AFNetworking的可以用AFURLConnectionOperation batchOfRequestOperations: progressBlock:completionBlock:

伊谢尔伦

Use GCD’s group

左手右手慢动作

It can be easily achieved using RxJava in Android.
Of course, you can also try the thread synchronization auxiliary class CountDownLatch implementation. For the use of CountDownLatch, you can refer to the following blog:
http://www.liuling123.com/2013/08/countdownlatch-demo.html

Ty80

I was shocked when I saw the answers from the masters. Faced with such problems, I often implement them manually. I usually set a resource variable, initialize the resource to ten, run a thread to monitor the number of resources, and then start concurrent tasks. Each time it is completed, Decrease a resource by one. When the resource reaches zero, stop the listening thread and complete subsequent operations.

This is a stupid way. I will use this when I don't know much about a language. After all, most languages ​​can be implemented this way.

Peter_Zhu

Java’s own concurrency framework supports solving the problem you mentioned, Future

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template