每个 iOS 应用程序都有个专门用来更新显示 UI 界面、处理用户的触摸事件的主线程,因此不能将其他太耗时的操作放在主线程中执行,不然会造成主线程堵塞(出现卡机现象),带来不好的用户体验。

一般的解决方案就是:将那些耗时的操作放到另外一个线程中去执行,多线程编程就是防止主线程堵塞和增加运行效率的最佳方法。

iOS 支持多个层次的多线程编程,层次越高的抽象程度越高,使用也越方便,也是 Apple 最推荐使用的方法。

​下面根据抽象层次从低到高依次列出 iOS 所支持的多线程编程方法:

  1. NSThread :是三种方法里面相对轻量级的,但需要管理线程的生命周期、同步、加锁问题,这会导致一定的性能开销

  2. NSOperation:是基于 OC 实现的,NSOperation 以面向对象的方式封装了需要执行的操作,不必关心线程管理、同步等问题。

    NSOperation 是一个抽象基类,iOS 提供了两种默认实现:NSInvocationOperation 和 NSBlockOperation,当然也可以自定义 NSOperation

  3. Grand Central Dispatch(简称 GCD ,iOS4 才开始支持):提供了一些新特性、运行库来支持多核并行编程,他的关注点更高:如何在多个 CPU 上提升效率

效果如下:

ViewController.h

 #import <UIKit/UIKit.h>

 @interface ViewController : UITableViewController
@property (copy, nonatomic) NSArray *arrSampleName; - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName; @end

ViewController.m

 #import "ViewController.h"
#import "FirstSampleViewController.h"
#import "SecondSampleViewController.h"
#import "ThirdSampleViewController.h" @interface ViewController ()
- (void)layoutUI;
@end @implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad]; [self layoutUI];
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName {
if (self = [super initWithStyle:UITableViewStyleGrouped]) {
self.navigationItem.title = @"多线程开发之一 NSThread";
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回首页" style:UIBarButtonItemStylePlain target:nil action:nil]; _arrSampleName = arrSampleName;
}
return self;
} - (void)layoutUI { } #pragma mark - UITableViewController相关方法重写
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 0.1;
} - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return ;
} - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_arrSampleName count];
} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.textLabel.text = _arrSampleName[indexPath.row];
return cell;
} - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
switch (indexPath.row) {
case : {
FirstSampleViewController *firstSampleVC = [FirstSampleViewController new];
[self.navigationController pushViewController:firstSampleVC animated:YES];
break;
}
case : {
SecondSampleViewController *secondSampleVC = [SecondSampleViewController new];
[self.navigationController pushViewController:secondSampleVC animated:YES];
break;
}
case : {
ThirdSampleViewController *thirdSampleVC = [ThirdSampleViewController new];
[self.navigationController pushViewController:thirdSampleVC animated:YES];
break; /*
类似堆栈的先进后出的原理:
返回到(上一级)、(任意级)、(根级)导航
[self.navigationController popViewControllerAnimated:YES];
[self.navigationController popToViewController:thirdSampleVC animated:YES];
[self.navigationController popToRootViewControllerAnimated:YES];
*/
}
default:
break;
}
} @end

UIImage+RescaleImage.h

 #import <UIKit/UIKit.h>

 @interface UIImage (RescaleImage)
/**
* 根据宽高大小,获取对应的缩放图片
*
* @param size 宽高大小
*
* @return 对应的缩放图片
*/
- (UIImage *)rescaleImageToSize:(CGSize)size; @end

UIImage+RescaleImage.m

 #import "UIImage+RescaleImage.h"

 @implementation UIImage (RescaleImage)

 - (UIImage *)rescaleImageToSize:(CGSize)size {
CGRect rect = CGRectMake(0.0, 0.0, size.width, size.height); UIGraphicsBeginImageContext(rect.size);
[self drawInRect:rect];
UIImage *imgScale = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext(); return imgScale;
} @end

KMImageData.h

 #import <Foundation/Foundation.h>

 @interface KMImageData : NSObject
@property (assign, nonatomic) NSInteger index;
@property (strong, nonatomic) NSData *data; - (instancetype)initWithData:(NSData *)data withIndex:(NSInteger)index; @end

KMImageData.m

 #import "KMImageData.h"

 @implementation KMImageData

 - (instancetype)initWithData:(NSData *)data withIndex:(NSInteger)index {
if (self = [super init]) {
_data = data;
_index = index;
}
return self;
} @end

FirstSampleViewController.h

 #import <UIKit/UIKit.h>

 @interface FirstSampleViewController : UIViewController
@property (assign, nonatomic) CGSize rescaleImageSize; @property (strong, nonatomic) IBOutlet UIImageView *imgV;
@property (strong, nonatomic) IBOutlet UIButton *btnLoadImage; @end

FirstSampleViewController.m

 #import "FirstSampleViewController.h"
#import "UIImage+RescaleImage.h" @interface FirstSampleViewController ()
- (void)layoutUI;
- (void)updateImage:(NSData *)imageData;
- (void)loadImageFromNetwork;
@end @implementation FirstSampleViewController - (void)viewDidLoad {
[super viewDidLoad]; [self layoutUI];
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} - (void)dealloc {
_imgV.image = nil;
} - (void)layoutUI {
CGFloat width = [[UIScreen mainScreen] bounds].size.width; //bounds 返回整个屏幕大小;applicationFrame 返回去除状态栏后的屏幕大小
CGFloat height = width * 150.0 / 190.0;
_rescaleImageSize = CGSizeMake(width, height); //NSString *path = [[NSBundle mainBundle] pathForResource:@"PictureNo@2x" ofType:@"png"];
//_imgV.image = [UIImage imageWithContentsOfFile:path]; _btnLoadImage.tintColor = [UIColor darkGrayColor];
_btnLoadImage.layer.masksToBounds = YES;
_btnLoadImage.layer.cornerRadius = 10.0;
_btnLoadImage.layer.borderColor = [UIColor grayColor].CGColor;
_btnLoadImage.layer.borderWidth = 1.0;
} - (void)updateImage:(NSData *)imageData {
UIImage *img = [UIImage imageWithData:imageData];
_imgV.image = [img rescaleImageToSize:_rescaleImageSize];
} - (void)loadImageFromNetwork {
NSURL *url = [NSURL URLWithString:@"http://images.apple.com/v/macbook/c/overview/images/hero_static_large.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url]; /*将数据显示到UI控件,注意只能在主线程中更新UI;
另外 performSelectorOnMainThread 方法是 NSObject 的分类方法,每个 NSObject 对象都有此方法;
它调用的 selector 方法是当前调用控件的方法,例如使用 UIImageView 调用的时候 selector 就是 UIImageView 的方法
withObject:代表调用方法的参数,不过只能传递一个参数(如果有多个参数请使用对象进行封装)
waitUntilDone:是否线程任务完成执行
*/
[self performSelectorOnMainThread:@selector(updateImage:)
withObject:data
waitUntilDone:YES];
} - (IBAction)loadImage:(id)sender {
//方法一:使用线程对象实例方法创建一个线程
//NSThread *thread = [[NSThread alloc] initWithTarget:self
// selector:@selector(loadImageFromNetwork)
// object:nil];
//[thread start]; //启动一个线程;注意启动一个线程并非就一定立即执行,而是处于就绪状态,当系统调度时才真正执行 //方法二:使用线程类方法创建一个线程
[NSThread detachNewThreadSelector:@selector(loadImageFromNetwork)
toTarget:self
withObject:nil];
} @end

FirstSampleViewController.xib

 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="7706" systemVersion="14E46" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7703"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="FirstSampleViewController">
<connections>
<outlet property="btnLoadImage" destination="sLs-f1-Gzc" id="kX8-J0-v0V"/>
<outlet property="imgV" destination="4Qp-uk-KAb" id="RM3-Ha-glh"/>
<outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/>
</connections>
</placeholder>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="PictureNo.png" translatesAutoresizingMaskIntoConstraints="NO" id="4Qp-uk-KAb">
<rect key="frame" x="205" y="225" width="190" height="150"/>
<constraints>
<constraint firstAttribute="height" constant="150" id="SIp-Wd-idU"/>
<constraint firstAttribute="height" constant="150" id="VwM-i1-atB"/>
<constraint firstAttribute="width" constant="190" id="mUh-Bu-tUd"/>
<constraint firstAttribute="width" constant="190" id="mdJ-1c-QFa"/>
<constraint firstAttribute="width" constant="190" id="sVS-bU-Ty9"/>
<constraint firstAttribute="height" constant="150" id="uMG-oN-J56"/>
<constraint firstAttribute="height" constant="150" id="vws-Qw-UrB"/>
</constraints>
<variation key="default">
<mask key="constraints">
<exclude reference="SIp-Wd-idU"/>
<exclude reference="VwM-i1-atB"/>
<exclude reference="mUh-Bu-tUd"/>
<exclude reference="mdJ-1c-QFa"/>
<exclude reference="sVS-bU-Ty9"/>
<exclude reference="uMG-oN-J56"/>
<exclude reference="vws-Qw-UrB"/>
</mask>
</variation>
</imageView>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="sLs-f1-Gzc">
<rect key="frame" x="230" y="500" width="140" height="50"/>
<constraints>
<constraint firstAttribute="width" constant="140" id="1jv-9K-mdH"/>
<constraint firstAttribute="height" constant="50" id="Q2w-vR-9ac"/>
</constraints>
<state key="normal" title="加载网络图片">
<color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/>
</state>
<connections>
<action selector="loadImage:" destination="-1" eventType="touchUpInside" id="fdy-Ln-5oS"/>
</connections>
</button>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="4Qp-uk-KAb" firstAttribute="leading" secondItem="i5M-Pr-FkT" secondAttribute="leading" constant="205" id="2a2-mS-WFa"/>
<constraint firstItem="sLs-f1-Gzc" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" id="ES4-wl-RBz"/>
<constraint firstItem="4Qp-uk-KAb" firstAttribute="centerY" secondItem="i5M-Pr-FkT" secondAttribute="centerY" id="MUJ-WA-sUf"/>
<constraint firstItem="4Qp-uk-KAb" firstAttribute="centerX" secondItem="sLs-f1-Gzc" secondAttribute="centerX" id="Q8a-1k-DzJ"/>
<constraint firstAttribute="bottom" secondItem="4Qp-uk-KAb" secondAttribute="bottom" constant="71" id="V0a-9y-Dwa"/>
<constraint firstAttribute="bottom" secondItem="sLs-f1-Gzc" secondAttribute="bottom" constant="50" id="VMG-CV-eeq"/>
<constraint firstItem="4Qp-uk-KAb" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" constant="-71" id="gqW-Wq-4Zv"/>
<constraint firstItem="sLs-f1-Gzc" firstAttribute="centerX" secondItem="i5M-Pr-FkT" secondAttribute="centerX" id="kNf-6d-EJ8"/>
</constraints>
<variation key="default">
<mask key="constraints">
<exclude reference="2a2-mS-WFa"/>
<exclude reference="V0a-9y-Dwa"/>
<exclude reference="gqW-Wq-4Zv"/>
<exclude reference="ES4-wl-RBz"/>
</mask>
</variation>
</view>
</objects>
<resources>
<image name="PictureNo.png" width="190" height="150"/>
</resources>
</document>

SecondSampleViewController.h

 #import <UIKit/UIKit.h>

 @interface SecondSampleViewController : UIViewController
@property (assign, nonatomic) CGSize rescaleImageSize;
@property (strong, nonatomic) NSMutableArray *mArrImageView; @property (strong, nonatomic) IBOutlet UIButton *btnLoadImage; @end

SecondSampleViewController.m

 #import "SecondSampleViewController.h"
#import "KMImageData.h"
#import "UIImage+RescaleImage.h" #define kRowCount 4
#define kColumnCount 3
#define kCellSpacing 10.0 @interface SecondSampleViewController ()
- (void)layoutUI;
- (void)updateImage:(KMImageData *)imageData;
-(KMImageData *)requestData:(NSInteger)imageIndex;
- (void)loadImageFromNetwork:(NSNumber *)imageIndex;
@end @implementation SecondSampleViewController - (void)viewDidLoad {
[super viewDidLoad]; [self layoutUI];
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} - (void)dealloc {
_mArrImageView = nil;
} - (void)layoutUI {
CGFloat width = ([[UIScreen mainScreen] bounds].size.width - ((kColumnCount + ) * kCellSpacing)) / kColumnCount;
_rescaleImageSize = CGSizeMake(width, width); CGFloat heightOfStatusAndNav = 20.0 + 44.0;
NSString *path = [[NSBundle mainBundle] pathForResource:@"PictureNo@2x" ofType:@"png"];
UIImage *img = [UIImage imageWithContentsOfFile:path];
_mArrImageView = [NSMutableArray arrayWithCapacity:kRowCount * kColumnCount];
//初始化多个图片视图
for (NSUInteger i=; i<kRowCount; i++) {
for (NSUInteger j=; j<kColumnCount; j++) {
UIImageView *imgV = [[UIImageView alloc] initWithFrame:
CGRectMake(_rescaleImageSize.width * j + kCellSpacing * (j+),
_rescaleImageSize.height * i + kCellSpacing * (i+) + heightOfStatusAndNav,
_rescaleImageSize.width,
_rescaleImageSize.height)];
imgV.image = img;
[self.view addSubview:imgV];
[_mArrImageView addObject:imgV];
}
} _btnLoadImage.tintColor = [UIColor darkGrayColor];
_btnLoadImage.layer.masksToBounds = YES;
_btnLoadImage.layer.cornerRadius = 10.0;
_btnLoadImage.layer.borderColor = [UIColor grayColor].CGColor;
_btnLoadImage.layer.borderWidth = 1.0;
} - (void)updateImage:(KMImageData *)imageData {
UIImage *img = [UIImage imageWithData:imageData.data];
UIImageView *imgVCurrent = _mArrImageView[imageData.index];
imgVCurrent.image = [img rescaleImageToSize:_rescaleImageSize];
} -(KMImageData *)requestData:(NSInteger)imageIndex {
//对于多线程操作,建议把线程操作放到 @autoreleasepool 中
@autoreleasepool {
if (imageIndex != kRowCount * kColumnCount - ) { //虽然设置了最后一个线程的优先级为1.0,但无法保证他是第一个加载的。所以我们这里让其他线程挂起0.5秒,这样基本能保证最后一个线程第一个加载,除非网络非常差的情况
[NSThread sleepForTimeInterval:0.5];
} NSURL *url = [NSURL URLWithString:@"http://images.apple.com/v/macbook/c/overview/images/hero_static_large.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
KMImageData *imageData = [[KMImageData alloc] initWithData:data
withIndex:imageIndex];
return imageData;
}
} - (void)loadImageFromNetwork:(NSNumber *)imageIndex {
NSLog(@"Current thread:%@",[NSThread currentThread]); /*将数据显示到UI控件,注意只能在主线程中更新UI;
另外 performSelectorOnMainThread 方法是 NSObject 的分类方法,每个 NSObject 对象都有此方法;
它调用的 selector 方法是当前调用控件的方法,例如使用 UIImageView 调用的时候 selector 就是 UIImageView 的方法
withObject:代表调用方法的参数,不过只能传递一个参数(如果有多个参数请使用对象进行封装)
waitUntilDone:是否线程任务完成执行
*/
[self performSelectorOnMainThread:@selector(updateImage:)
withObject:[self requestData:[imageIndex integerValue]]
waitUntilDone:YES];
} - (IBAction)loadImage:(id)sender {
for (NSUInteger i=, len=kRowCount * kColumnCount; i<len; i++) {
NSThread *thread = [[NSThread alloc] initWithTarget:self
selector:@selector(loadImageFromNetwork:)
object:[NSNumber numberWithInteger:i]];
thread.name = [NSString stringWithFormat:@"Thread %lu", (unsigned long)i];
thread.threadPriority = i == len- ? 1.0 : 0.0; //设置线程优先级;0.0-1.0,值越高优先级越高,这样可以提高他被优先加载的机率,但是他也未必就第一个加载。因为首先其他线程是先启动的,其次网络状况我们没办法修改
[thread start];
}
} @end

SecondSampleViewController.xib

 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="7706" systemVersion="14E46" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7703"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="SecondSampleViewController">
<connections>
<outlet property="btnLoadImage" destination="F5h-ZI-gGL" id="I40-e2-bAa"/>
<outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/>
</connections>
</placeholder>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="F5h-ZI-gGL">
<rect key="frame" x="230" y="530" width="140" height="50"/>
<constraints>
<constraint firstAttribute="height" constant="50" id="HWd-Xc-Wk7"/>
<constraint firstAttribute="width" constant="140" id="vrH-qE-PNK"/>
</constraints>
<state key="normal" title="加载网络图片">
<color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/>
</state>
<connections>
<action selector="loadImage:" destination="-1" eventType="touchUpInside" id="Hgw-q8-lHy"/>
</connections>
</button>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
<constraints>
<constraint firstAttribute="bottom" secondItem="F5h-ZI-gGL" secondAttribute="bottom" constant="20" id="jPY-fY-9XJ"/>
<constraint firstAttribute="centerX" secondItem="F5h-ZI-gGL" secondAttribute="centerX" id="rH1-sV-pST"/>
</constraints>
</view>
</objects>
</document>

ThirdSampleViewController.h

 #import <UIKit/UIKit.h>

 @interface ThirdSampleViewController : UIViewController
@property (assign, nonatomic) CGSize rescaleImageSize;
@property (strong, nonatomic) NSMutableArray *mArrImageView;
@property (strong, nonatomic) NSMutableArray *mArrThread; @property (strong, nonatomic) IBOutlet UIButton *btnLoadImage;
@property (strong, nonatomic) IBOutlet UIButton *btnStopLoadImage; @end

ThirdSampleViewController.m

 #import "ThirdSampleViewController.h"
#import "KMImageData.h"
#import "UIImage+RescaleImage.h" #define kRowCount 4
#define kColumnCount 3
#define kCellSpacing 10.0 @interface ThirdSampleViewController ()
- (void)layoutUI;
- (void)updateImage:(KMImageData *)imageData;
-(KMImageData *)requestData:(NSInteger)imageIndex;
- (void)loadImageFromNetwork:(NSNumber *)imageIndex;
@end @implementation ThirdSampleViewController - (void)viewDidLoad {
[super viewDidLoad]; [self layoutUI];
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} - (void)dealloc {
_mArrImageView = nil;
_mArrThread = nil;
} - (void)layoutUI {
CGFloat width = ([[UIScreen mainScreen] bounds].size.width - ((kColumnCount + ) * kCellSpacing)) / kColumnCount;
_rescaleImageSize = CGSizeMake(width, width); CGFloat heightOfStatusAndNav = 20.0 + 44.0;
NSString *path = [[NSBundle mainBundle] pathForResource:@"PictureNo@2x" ofType:@"png"];
UIImage *img = [UIImage imageWithContentsOfFile:path];
_mArrImageView = [NSMutableArray arrayWithCapacity:kRowCount * kColumnCount];
//初始化多个图片视图
for (NSUInteger i=; i<kRowCount; i++) {
for (NSUInteger j=; j<kColumnCount; j++) {
UIImageView *imgV = [[UIImageView alloc] initWithFrame:
CGRectMake(_rescaleImageSize.width * j + kCellSpacing * (j+),
_rescaleImageSize.height * i + kCellSpacing * (i+) + heightOfStatusAndNav,
_rescaleImageSize.width,
_rescaleImageSize.height)];
imgV.image = img;
[self.view addSubview:imgV];
[_mArrImageView addObject:imgV];
}
} void (^beautifulButton)(UIButton *, UIColor *) = ^(UIButton *btn, UIColor *tintColor) {
btn.tintColor = tintColor;
btn.layer.masksToBounds = YES;
btn.layer.cornerRadius = 10.0;
btn.layer.borderColor = [UIColor grayColor].CGColor;
btn.layer.borderWidth = 1.0;
}; beautifulButton(_btnLoadImage, [UIColor darkGrayColor]);
beautifulButton(_btnStopLoadImage, [UIColor redColor]);
} - (void)updateImage:(KMImageData *)imageData {
UIImage *img = [UIImage imageWithData:imageData.data];
UIImageView *imgVCurrent = _mArrImageView[imageData.index];
imgVCurrent.image = [img rescaleImageToSize:_rescaleImageSize];
} -(KMImageData *)requestData:(NSInteger)imageIndex {
//对于多线程操作,建议把线程操作放到 @autoreleasepool 中
@autoreleasepool {
if (imageIndex != kRowCount * kColumnCount - ) { //虽然设置了最后一个线程的优先级为1.0,但无法保证他是第一个加载的。所以我们这里让其他线程挂起0.5秒,这样基本能保证最后一个线程第一个加载,除非网络非常差的情况
[NSThread sleepForTimeInterval:0.5];
} NSURL *url = [NSURL URLWithString:@"http://images.apple.com/v/macbook/c/overview/images/hero_static_large.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
KMImageData *imageData = [[KMImageData alloc] initWithData:data
withIndex:imageIndex];
return imageData;
}
} - (void)loadImageFromNetwork:(NSNumber *)imageIndex { //子线程中执行
//线程状态:thread.isExecuting(是否执行中)、thread.isFinished(是否已完成)、thread.isCancelled(是否已取消)
//thread.isMainThread(是否主线程)、[NSThread isMultiThreaded](是否多线程) KMImageData *imageData = [self requestData:[imageIndex integerValue]]; NSThread *thread = _mArrThread[[imageIndex integerValue]];
if (thread.isCancelled) { //判断线程是否已经取消,如是就退出当前线程;这里注意需让 exit 操作有足够的时间进行占用资源的释放,否则有可能出现异常;比如 Demo 中:当点击「停止加载」按钮后,再次快速点击「加载网络图片」按钮
NSLog(@"Current thread:%@ will be cancelled.", thread);
[NSThread exit];
} else {
// //在后台执行一个方法,本质就是重新创建一个线程来执行方法
// [self performSelectorInBackground:@selector(updateImage:) withObject:imageData];
//
// /*将数据显示到UI控件,注意只能在主线程中更新UI;
// 另外 performSelectorOnMainThread 方法是 NSObject 的分类方法,每个 NSObject 对象都有此方法;它调用的 selector 方法是当前调用控件的方法,例如使用 UIImageView 调用的时候 selector 就是 UIImageView 的方法
// withObject:代表调用方法的参数,不过只能传递一个参数(如果有多个参数请使用对象进行封装)
// waitUntilDone:是否线程任务完成后执行
// */
// [self performSelectorOnMainThread:@selector(updateImage:)
// withObject:imageData
// waitUntilDone:YES]; @try {
//在指定的线程上执行一个方法,需要用户创建一个线程对象实例
[self performSelector:@selector(updateImage:)
onThread:thread
withObject:imageData
waitUntilDone:YES];
}
@catch (NSException *exception) {
NSLog(@"Exception: %@", [exception description]);
}
}
} - (IBAction)loadImage:(id)sender {
NSUInteger len = kRowCount * kColumnCount;
_mArrThread = [NSMutableArray arrayWithCapacity:len]; //循环创建多个线程
for (NSUInteger i=; i<len; i++) {
NSThread *thread = [[NSThread alloc] initWithTarget:self
selector:@selector(loadImageFromNetwork:)
object:[NSNumber numberWithInteger:i]];
thread.name = [NSString stringWithFormat:@"Thread %lu", (unsigned long)i];
thread.threadPriority = i == len- ? 1.0 : 0.0; //设置线程优先级;0.0-1.0,值越高优先级越高,这样可以提高他被优先加载的机率,但是他也未必就第一个加载。因为首先其他线程是先启动的,其次网络状况我们没办法修改
[_mArrThread addObject:thread];
} //循环启动线程
for (NSUInteger i=; i<len; i++) {
NSThread *thread = _mArrThread[i];
[thread start];
}
} - (IBAction)stopLoadImage:(id)sender { //主线程中执行
for (NSUInteger i=, len=kRowCount * kColumnCount; i<len; i++) {
NSThread *thread = _mArrThread[i];
if (!thread.isFinished) { //判断线程是否完成,如果没有完成则设置为取消状态;取消状态仅仅是改变了线程状态而言,并不能终止线程
[thread cancel];
}
}
} @end

ThirdSampleViewController.xib

 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="7706" systemVersion="14E46" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7703"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="ThirdSampleViewController">
<connections>
<outlet property="btnLoadImage" destination="F5h-ZI-gGL" id="I40-e2-bAa"/>
<outlet property="btnStopLoadImage" destination="gnu-KE-bGq" id="tOA-t9-OA9"/>
<outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/>
</connections>
</placeholder>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="F5h-ZI-gGL">
<rect key="frame" x="20" y="530" width="130" height="50"/>
<constraints>
<constraint firstAttribute="height" constant="50" id="HWd-Xc-Wk7"/>
<constraint firstAttribute="width" constant="130" id="vrH-qE-PNK"/>
</constraints>
<state key="normal" title="加载网络图片">
<color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/>
</state>
<connections>
<action selector="loadImage:" destination="-1" eventType="touchUpInside" id="Hgw-q8-lHy"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="gnu-KE-bGq">
<rect key="frame" x="450" y="530" width="130" height="50"/>
<constraints>
<constraint firstAttribute="height" constant="50" id="1R7-22-hMk"/>
<constraint firstAttribute="width" constant="130" id="64l-yF-IFO"/>
</constraints>
<state key="normal" title="停止加载">
<color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/>
</state>
<connections>
<action selector="loadImage:" destination="-1" eventType="touchUpInside" id="PyX-RW-cbL"/>
<action selector="stopLoadImage:" destination="-1" eventType="touchUpInside" id="1Xa-Ek-D4B"/>
</connections>
</button>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="F5h-ZI-gGL" firstAttribute="leading" secondItem="i5M-Pr-FkT" secondAttribute="leading" constant="20" id="Glo-vW-SXd"/>
<constraint firstAttribute="trailing" secondItem="gnu-KE-bGq" secondAttribute="trailing" constant="20" id="IdF-1v-bg2"/>
<constraint firstAttribute="bottom" secondItem="gnu-KE-bGq" secondAttribute="bottom" constant="20" id="cyx-dg-K8M"/>
<constraint firstAttribute="bottom" secondItem="F5h-ZI-gGL" secondAttribute="bottom" constant="20" id="jPY-fY-9XJ"/>
<constraint firstAttribute="centerX" secondItem="F5h-ZI-gGL" secondAttribute="centerX" id="rH1-sV-pST"/>
</constraints>
<variation key="default">
<mask key="constraints">
<exclude reference="rH1-sV-pST"/>
</mask>
</variation>
</view>
</objects>
</document>

AppDelegate.h

 #import <UIKit/UIKit.h>

 @interface AppDelegate : UIResponder <UIApplicationDelegate>

 @property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) UINavigationController *navigationController; @end

AppDelegate.m

 #import "AppDelegate.h"
#import "ViewController.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
_window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
ViewController *viewController = [[ViewController alloc] initWithSampleNameArray:@[@"请求单张网络图片(解决线程阻塞)", @"请求多张网络图片(多个线程并发)", @"请求多张网络图片(线程状态)"]];
_navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
_window.rootViewController = _navigationController;
//[_window addSubview:_navigationController.view]; //当_window.rootViewController关联时,这一句可有可无
[_window makeKeyAndVisible];
return YES;
} - (void)applicationWillResignActive:(UIApplication *)application {
} - (void)applicationDidEnterBackground:(UIApplication *)application {
} - (void)applicationWillEnterForeground:(UIApplication *)application {
} - (void)applicationDidBecomeActive:(UIApplication *)application {
} - (void)applicationWillTerminate:(UIApplication *)application {
} @end

输出结果:

 -- ::38.945 NSThreadDemo[:]  INFO: Reveal Server started (Protocol Version ).
-- ::57.863 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60cd1f80>{number = , name = Thread }
-- ::57.863 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60c74800>{number = , name = Thread }
-- ::57.863 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60cb8f30>{number = , name = Thread }
-- ::57.863 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60cb8500>{number = , name = Thread }
-- ::57.864 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60cd0c60>{number = , name = Thread }
-- ::57.865 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60dee540>{number = , name = Thread }
-- ::57.864 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60cd2150>{number = , name = Thread }
-- ::57.866 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60daf730>{number = , name = Thread }
-- ::57.866 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60db8530>{number = , name = Thread }
-- ::57.866 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60f3f7e0>{number = , name = Thread }
-- ::57.866 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60db2390>{number = , name = Thread }
-- ::57.867 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60f231c0>{number = , name = Thread } -- ::07.073 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f63010930>{number = , name = Thread } will be cancelled.
-- ::07.691 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60df0210>{number = , name = Thread } will be cancelled.
-- ::07.697 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60db8ee0>{number = , name = Thread } will be cancelled.
-- ::07.729 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60db2390>{number = , name = Thread } will be cancelled.
-- ::07.857 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f63011190>{number = , name = Thread } will be cancelled.
-- ::08.025 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f6300c2d0>{number = , name = Thread } will be cancelled.
-- ::08.047 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60dd4200>{number = , name = Thread } will be cancelled.
-- ::08.191 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60db8ee0>{number = , name = Thread } will be cancelled.
-- ::08.250 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f630110b0>{number = , name = Thread } will be cancelled.
-- ::08.416 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60df7bc0>{number = , name = Thread } will be cancelled.
-- ::08.464 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60dc5ca0>{number = , name = Thread } will be cancelled.
-- ::08.495 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f63011190>{number = , name = Thread } will be cancelled.
-- ::08.661 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60df0210>{number = , name = Thread } will be cancelled.
-- ::10.033 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f60da3330>{number = , name = Thread } will be cancelled.
-- ::10.056 NSThreadDemo[:] Current thread:<NSThread: 0x7f9f63010930>{number = , name = Thread } will be cancelled.

多线程开发之一 NSThread的更多相关文章

  1. iOS多线程开发--NSThread NSOperation GCD

    多线程 当用户播放音频.下载资源.进行图像处理时往往希望做这些事情的时候其他操作不会被中 断或者希望这些操作过程中更加顺畅.在单线程中一个线程只能做一件事情,一件事情处理不完另一件事就不能开始,这样势 ...

  2. iOS多线程开发资源抢夺和线程间的通讯问题

    说到多线程就不得不提多线程中的锁机制,多线程操作过程中往往多个线程是并发执行的,同一个资源可能被多个线程同时访问,造成资源抢夺,这个过程中如果没有锁机制往往会造成重大问题.举例来说,每年春节都是一票难 ...

  3. iOS多线程开发

    概览 大家都知道,在开发过程中应该尽可能减少用户等待时间,让程序尽可能快的完成运算.可是无论是哪种语言开发的程序最终往往转换成汇编语言进而解释成机器码来执行.但是机器码是按顺序执行的,一个复杂的多步操 ...

  4. ios多线程开发的常用三种方式

    1.NSThread 2.NSOperationQueue 3.GCD NSThread: 创建方式主要有两种: [NSThread detachNewThreadSelector:@selector ...

  5. 玩转iOS开发 - 多线程开发

    前言 本文主要介绍iOS多线程开发中使用的主要技术:NSOperation, GCD. NSThread, pthread. 内容依照开发中的优先推荐使用的顺序进行介绍,涉及多线程底层知识比較多的NS ...

  6. [ios2]使用NSOperationQueue简化多线程开发和队列的优先级 【转】

    多线程开发是一件需要特别精心的事情,即使是对有多年开发经验的工程师来说. 为了能让初级开发工程师也能使用多线程,同时还要简化复杂性.各种编程工具提供了各自的办法.对于iOS来说,建议在尽可能的情况下避 ...

  7. ios多线程开发总结

    1>无论使用哪种方法进行多线程开发,每个线程启动后并不一定立即执行相应的操作,具体什么时候由系统调度(CPU空闲时就会执行). 2>更新UI应该在主线程(UI线程)中进行,并且推荐使用同步 ...

  8. 多线程开发之三 GCD

    NSThread.NSOperation.GCD 总结: 无论使用哪种方法进行多线程开发,每个线程启动后并不一定立即执行相应的操作,具体什么时候由系统调度(CPU 空闲时就会执行) 更新 UI 应该在 ...

  9. 多线程开发之二 NSOperation

    效果如下: ViewController.h #import <UIKit/UIKit.h> @interface ViewController : UITableViewControll ...

随机推荐

  1. 20172302 《Java软件结构与数据结构》第四周学习总结

    2018年学习总结博客总目录:第一周 第二周 第三周 第四周 教材学习内容总结 第六章 列表 1.列表是对象的有序集合,在 List 界面中定义. List 接口表示集合框架中的列表.列表可以具有重复 ...

  2. 各种Oracle索引类型介绍

    逻辑上:Single column 单行索引Concatenated 多行索引Unique 唯一索引NonUnique 非唯一索引Function-based函数索引Domain 域索引 物理上:Pa ...

  3. Android开发中遇到的问题(四)——Android中WARNING: Application does not specify an API level requirement!的解决方法

    今天在手机上调试运行Andorid项目时,发现Console打印出"WARNING: Application does not specify an API level requiremen ...

  4. web架构延变

    在现代的软件系统中,几乎所有的系统都使用到了数据库,不论是关系型数据,例如MySql.SQLite.Oracle.SQLServer等,还是非关系性数据,例如mongoDB.redis等.本文已web ...

  5. [web前端] 去哪儿网前端架构师司徒正美:如何挑选适合的前端框架?

    原文地址: https://www.jianshu.com/p/6327d4280e3b 最近几年,前端技术迅猛发展,差不多每年都会冒出一款主流的框架. 每次新开业务线或启动新项目时,首先第一件事就是 ...

  6. Asp.Net Core 自定义设置Http缓存处理

    一.使用中间件 拦截请求自定义输出文件 输出前自定义指定响应头 public class OuterImgMiddleware { public static string RootPath { ge ...

  7. windows和linux文件输 - ftp

    1. linux到linux的复制直接用scp命令 但是windows下就麻烦点, 安装winscp, 配置用户名和密码即可随意拖拽了. 下载地址: 需要linux电脑的用户名和密码即可 2. win ...

  8. 10个优秀Objective-C和iOS开发在线视频教程

    如果你自己开发iOS应用,你肯定会发现网上有很多资源.学习编程的一个最好的方法就是自己写代码,而开始写代码的最快的方式就是看其他人怎么写.我们从海量视频和学习网站中整理出了我们认为对你学习Object ...

  9. 关于PHP中的webshell

    一.webshell简介 webshell就是以asp.php.jsp或者cgi等网页文件形式存在的一种命令执行环境,也可以将其称做为一种网页后门.黑客在入侵了一个网站后,通常会将asp或php后门文 ...

  10. vmlinux,zImage,bzImage,vmlinuz,uImage,关系

    zImage和uImage的区别 一.vmlinuz vmlinuz是可引导的.压缩的内核.“vm”代表“Virtual Memory”.Linux 支持虚拟内存,不像老的操作系统比如DOS有640K ...