// 1. use GCD for thread processing ---- use dispatch_async to prevent time-consuming operations on the interface from getting stuck. Perform thread operations first, and then notify the main thread to update the interface dispatch_async (dispatch_get_global_queue (dispatch_queue_priority ), ^ {// NSInteger row = [indexPath row]; NSString * str = [self. array objectAtIndex: row]; NSURL * url = [NSURL URLWithString: str]; NSData * imageData = [NSData dataWithContentsOfURL: url]; UIImage * image = [[UIImage alloc] initWithData: imageData]; if ( Image! = Nil) {dispatch_async (dispatch_get_main_queue (), ^ {cell. imageView. image = image; [cell. activityIndicatorView stopAnimating]; // reloadData cannot be used here. Although the interface is updated, you will find many threads that cause the app to crash. // [Self. tableView reloadData]; // operation for updating the interface });}});
2.
// 2 Use GCD for thread processing // dispatch_group_async can monitor whether a group of events are completed, and then notify the execution of other operations dispatch_queue_t queue = dispatch_get_global_queue (success, 0 ); dispatch_group_t group = dispatch_group_create (); _ block UIImage * image; dispatch_group_async (group, queue, ^ {NSInteger row = [indexPath row]; NSString * str = [self. array objectAtIndex: row]; NSURL * url = [NSURL URLWithString: str]; NSData * imageD Ata = [NSData dataWithContentsOfURL: url]; image = [[UIImage alloc] initWithData: imageData] ;}); // the following update operation can be performed only after the preceding operation is complete. Dispatch_group_policy (group, queue, ^ {cell. imageView. image = image; [cell. activityIndicatorView stopAnimating];});
3.
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); });
16:20:33. 967 gcdTest [45547: 11203] dispatch_async1
16:20:35. 967 gcdTest [45547: 11303] dispatch_async2
16:20:35. 967 gcdTest [45547: 11303] dispatch_barrier_async
16:20:40. 970 gcdTest [45547: 11303] dispatch_async3
4.
4. dispatch_apply
Execute a code snippet N times.
Dispatch_apply (5, globalQ, ^ (size_t index ){
// Execute 5 times
});