一、基本使用

1.多线程的优缺点

多线程的优点
能适当提高程序的执行效率
能适当提高资源利用率(CPU、内存利用率)
多线程的缺点
开启线程需要占用一定的内存空间(默认情况下,主线程占用1M,子线程占用512KB),如果开启大量的线程,会占用大量的内存空间,降低程序的性能
线程越多,CPU在调度线程上的开销就越大
程序设计更加复杂:比如线程之间的通信、多线程的数据共享
 
 
2.多线程在iOS开发中的应用
什么是主线程
一个iOS程序运行后,默认会开启1条线程,称为“主线程”或“UI线程”
 
主线程的主要作用
显示\刷新UI界面
处理UI事件(比如点击事件、滚动事件、拖拽事件等)
 
主线程的使用注意
别将比较耗时的操作放到主线程中
耗时操作会卡住主线程,严重影响UI的流畅度,给用户一种“卡”的坏体验
 
 
 //
// ViewController.m
// IOS_0116_NSThread
//
// Created by ma c on 16/1/16.
// Copyright (c) 2016年 博文科技. All rights reserved.
// #import "ViewController.h"
#import <pthread.h> /*
线程的实现方案
pthread
NSThread
GCD
NSOperation
*/
@interface ViewController () @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; //[self pthread]; }
#pragma mark - 创建线程NSThread
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// [self createThread1];
// [self createThread2];
[self createThread3]; }
#pragma mark - 创建线程3
- (void)createThread3
{
//隐式创建线程
[self performSelector:@selector(download:) withObject:@"http:www.bowen.cn"];
[self download:@"http:www.bowen.cn"]; [self performSelectorInBackground:@selector(download:) withObject:@"http:www.bowen.cn"]; [self performSelector:@selector(download:) onThread:[NSThread mainThread] withObject:@"http:www.bowen.cn" waitUntilDone:nil]; } #pragma mark - 创建线程2
- (void)createThread2
{
//创建后并启动线程
[NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"http:www.bowen.cn"];
}
- (void)download:(NSString *)url
{
NSLog(@"\ndownload----%@",[NSThread mainThread]); NSLog(@"\ndownload----%@----%@",url,[NSThread currentThread]);
} #pragma mark - 创建线程1
//启动线程 - 进入就绪状态 -(CPU调度当前线程)- 运行状态 - 线程任务完毕,自动进入死亡状态
// -调用sleep方法或者等待同步锁 - 阻塞状态
- (void)createThread1
{
//创建线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(download) object:nil];
//设置线程的名字
thread.name = @"下载线程";
//当前线程是否是主线程
[thread isMainThread];
//启动线程
[thread start]; //判断当前方法是否是在主线程主线程中执行
[NSThread isMainThread];
} - (void)download
{
NSLog(@"\ndownload----%@",[NSThread mainThread]); //阻塞线程
[NSThread sleepForTimeInterval:];
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:]]; NSLog(@"\ndownload----%@",[NSThread currentThread]); //强制停止线程
[NSThread exit];
NSLog(@"\ndownload----%@",@"exit");
} #pragma mark - pthread
- (void)pthread
{
NSLog(@"\nviewDidLoad-------%@",[NSThread currentThread]); //创建线程
pthread_t myRestrict;
pthread_create(&myRestrict, NULL, run, NULL);
} void *run(void *data)
{
NSLog(@"\nrun-------%@",[NSThread currentThread]); return NULL;
} @end

二、线程安全

 //
// ViewController.m
// IOS_0117_线程的安全隐患
//
// Created by ma c on 16/1/17.
// Copyright (c) 2016年 博文科技. All rights reserved.
// #import "ViewController.h" @interface ViewController () @property (nonatomic, strong) NSThread *thread1;
@property (nonatomic, strong) NSThread *thread2; //剩余票数
@property (nonatomic, assign) int leftTicketCount; @end @implementation ViewController
/*
资源共享
一块资源可能会被多个线程共享,也就是多个线程可能会访问[同一块资源] 比如多个线程访问同一个对象、同一个变量、同一个文件 当多个线程访问同一块资源时,很容易引发[数据错乱和数据安全]问题 */ - (void)viewDidLoad {
[super viewDidLoad]; self.leftTicketCount = ; self.thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread1.name = @"1号窗口";
self.thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread2.name = @"2号窗口"; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.thread1 start];
[self.thread2 start];
}
/*
互斥锁使用格式
@synchronized(锁对象) { // 需要锁定的代码 }
注意:锁定1份代码只用1把锁,用多把锁是无效的 互斥锁的优缺点
优点:能有效防止因多线程抢夺资源造成的数据安全问题
缺点:需要消耗大量的CPU资源 互斥锁的使用前提:多条线程抢夺同一块资源 相关专业术语:线程同步
线程同步的意思是:多条线程在同一条线上执行(按顺序地执行任务)
互斥锁,就是使用了线程同步技术 */
- (void)saleTicket
{
while () { @synchronized(self){ //开始枷锁 小括号里面放的是锁对象
int count = self.leftTicketCount;
if (count>) {
self.leftTicketCount = count -;
NSLog(@"%@卖了一张票,剩余%d张票",[NSThread currentThread].name, self.leftTicketCount);
}else{
return; //退出循环 break
} }//解锁 }
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end

三、线程间通信

 //
// ViewController.m
// IOS_0117_线程间通信
//
// Created by ma c on 16/1/17.
// Copyright (c) 2016年 博文科技. All rights reserved.
// #import "ViewController.h" @interface ViewController () @property (nonatomic, strong) UIImageView *imgView; @end @implementation ViewController /*
什么叫做线程间通信
在1个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信 线程间通信的体现
1个线程传递数据给另1个线程
在1个线程中执行完特定任务后,转到另1个线程继续执行任务 线程间通信常用方法
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait; */
- (void)viewDidLoad {
[super viewDidLoad]; self.imgView = [[UIImageView alloc] initWithFrame:CGRectMake(, , , )];
//self.imgView.image = [UIImage imageNamed:@"1.png"];
self.imgView.backgroundColor = [UIColor cyanColor];
[self.view addSubview:self.imgView]; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self performSelectorInBackground:@selector(downloadPicture) withObject:nil]; } - (void)downloadPicture
{ NSLog(@"\ndownload----%@",[NSThread currentThread]);
//1.图片地址
NSString *urlStr = @"1.png";
//NSURL *url = [NSURL URLWithString:urlStr];
//2.根据地址下载图片的二进制数据
//NSData *data = [NSData dataWithContentsOfURL:url];
//3.设置图片
UIImage *image = [UIImage imageNamed:urlStr];
//self.imgView.image = [UIImage imageWithData:data];
//4.回到主线程,刷新UI界面(为了线程安全)
[self performSelectorOnMainThread:@selector(downloadFinished:) withObject:image waitUntilDone:YES];
}
- (void)downloadFinished:(UIImage *)image
{ NSLog(@"\ndownloadFinished----%@",[NSThread currentThread]);
self.imgView.image = image; }
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end

iOS UI-线程(NSThread)及其安全隐患与通信的更多相关文章

  1. IOS UI多线程 NSThread 下载并显示图片到UIImageView

    效果图 @property (weak,nonatomic)IBOutletUILabel *downLabelInfo; @property (weak,nonatomic)IBOutletUIIm ...

  2. iOS UI异步更新:dispatch_async 与 dispatch_get_global_queue 的使用方法

    GCD (Grand Central Dispatch) 是Apple公司开发的一种技术,它旨在优化多核环境中的并发操作并取代传统多线程的编程模式. 在Mac OS X 10.6和IOS 4.0之后开 ...

  3. iOS-线程&&进程的深入理解

    进程基本概念 进程就是一个正在运行的一个应用程序; 每一个进度都是独立的,每一个进程均在专门且手保护的内存空间内; iOS是怎么管理自己的内存的,见博客:博客地址 在Linux系统中,想要新开启一个进 ...

  4. iOS GCD NSOperation NSThread等多线程各种举例详解(拷贝)

    2年多的iOS之路匆匆而过,期间也拜读来不少大神的博客,近来突然为自己一直做伸手党感到羞耻,是时候回馈社会.回想当年自己还是小白的时候,照着一些iOS多线程教程学,也只是照抄,只知其然.不知其所以然. ...

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

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

  6. IOS任务管理之NSThread使用

    前言: 无论是Android还是IOS都会使用到多任务,多任务的最小单元那就是线程,今天学习总结一下IOS的NSThread使用. NSThread使用? 第一种方式实例化 //selector :线 ...

  7. iOS GCD NSOperation NSThread等多线程各种举例详解

    废话就不多说,直接上干货.如下图列举了很多多线程的知识点,每个按钮都写有对应的详细例子,并对运行结果进行分析,绝对拿实践结果来说话.如果各位道友发现错误之处还请指正.附上demo下载地址

  8. iOS:多线程NSThread的详细使用

    NSThread具体使用:直接继承NSObject NSThread:. 优点:NSThread 是轻量级的,使用简单 缺点:需要自己管理线程的生命周期.线程同步.线程同步对数据的加锁会有一定的系统开 ...

  9. iOS开发 - 线程与进程的认识与理解

    进程: 进程是指在系统中正在运行的一个应用程序,比如同时打开微信和Xcode,系统会分别启动2个进程; 每个进程之间是独立的,每个进程均运行在其专用且受保护的内存空间内; 线程: 一个进程要想执行任务 ...

随机推荐

  1. python re.sub 括号匹配替换匹配到的内容后接数字

    如果代码为: text = re.sub(r'(?<=[{])([a-z]+)6(?=[}])', r'\13', text) 上面代码会报错,因为没有组合13,所以不能获得组合13的内容. 但 ...

  2. Rain on your Parade---hdu2389(HK求最大匹配)

    题目链接 题意:有n个客人,m把雨伞,在t秒之后将会下雨,给出每个客人的坐标和每秒行走的距离,以及雨伞的位置,问t秒后最多有几个客人可以拿到雨伞? 就是求最大匹配的  Hopcroft-Karp复杂度 ...

  3. 用MongoDB取代RabbitMQ(转)

    原文:http://blog.nosqlfan.com/html/3223.html RabbitMQ是当成应用比较广泛的队列服务系统,其配套的客户端和监控运维方案也比较成熟.BoxedIce的队列服 ...

  4. centos DNS服务搭建 DNS原理 使用bind搭建DNS服务器 配置DNS转发 配置主从 安装dig工具 DHCP dhclient 各种域名解析记录 mydns DNS动态更新 第三十节课

    centos  DNS服务搭建  DNS原理  使用bind搭建DNS服务器 配置DNS转发 配置主从  安装dig工具  DHCP  dhclient  各种域名解析记录  mydns DNS动态更 ...

  5. 001-ant design安装及快速入门【基于纯antd的基本项目搭建】

    一.安装使用 1.1.安装 推荐使用 npm 或 yarn 的方式进行开发 npm install antd --save yarn add antd 1.2.浏览器引入 在浏览器中使用 script ...

  6. 《TP5.0学习笔记---模型篇》

    https://blog.csdn.net/self_realian/article/details/78596261 一.什么是模型 为什么我们要在项目中使用模型,其实我们知道,我们可以直接在控制器 ...

  7. Spark提交应用程序之Spark-Submit分析

    1.提交应用程序 在提交应用程序的时候,用到 spark-submit 脚本.我们来看下这个脚本: if [ -z "${SPARK_HOME}" ]; then export S ...

  8. PAT 1094 The Largest Generation[bfs][一般]

    1094 The Largest Generation(25 分) A family hierarchy is usually presented by a pedigree tree where a ...

  9. mydumper原理介绍

      mydumper的安装:http://www.cnblogs.com/lizhi221/p/7010174.html   mydumper介绍   MySQL自身的mysqldump工具支持单线程 ...

  10. php生成二维码的几种方式

    一些php生成二维码的方式:1.google开放api:2.php类库PHP QR Code:3.libqrencode:4.QRcode Perl CGI & PHP scripts 1.g ...